celery excess argument [True, False] subtask, callback, How do I remove them? - callback

How to ignore arguments allowed [True, False] when you pass an argument ((status_id)) to function success ()?
status_id=11
callback = success.subtask((status_id,))
chord(results)(callback)
#app.task(routing_key="message_status", queue="message_status")
def success(status_id):
try:
global db
db = connection()
db.query(MessageTask).filter_by(id=status_id).update({
'status': 'success',
'date': datetime.now().strftime("%Y-%m-%d %H:%M:%S")
})
db.commit()
return True
except Exception as e:
print(e)
status_id comes in result of [[True, False], '11']. How do I remove them?

Related

Can Protractor ignores the timeouts of 3rd party plugin in angular?

I'm using amchart to show my data analytics in the Angular app. If I run an E2E test on that page that contains the amchart plugin, it's not able to finish (script timeout) cause it using real-time updates for charts (dynamic)...
This command 'getAllAngularTestabilities()' in console shows that has been pendingMacrotasks on page, so if the Protractor not working here, it's totally okay.
[Testability]
0: Testability
taskTrackingZone: TaskTrackingZoneSpec {name: "TaskTrackingZone", microTasks: Array(0), macroTasks: Array(3), eventTasks: Array(474), properties: {…}}
_callbacks: []
_didWork: true
_isZoneStable: true
_ngZone: NgZone
hasPendingMacrotasks: true
hasPendingMicrotasks: false
isStable: true
lastRequestAnimationFrameId: -1
nativeRequestAnimationFrame: ƒ requestAnimationFrame()
onError: EventEmitter_ {_isScalar: false, observers: Array(1), closed: false, isStopped: false, hasError: false, …}
onMicrotaskEmpty: EventEmitter_ {_isScalar: false, observers: Array(1), closed: false, isStopped: false, hasError: false, …}
onStable: EventEmitter_ {_isScalar: false, observers: Array(2), closed: false, isStopped: false, hasError: false, …}
onUnstable: EventEmitter_ {_isScalar: false, observers: Array(1), closed: false, isStopped: false, hasError: false, …}
shouldCoalesceEventChangeDetection: false
I have 3 charts on that page, so I checked what NgZone says: Coming to a request in every second, and I can't turn off them. I'm trying to find the solution in amchart's documentation but I haven't found anything yet...
ZONE pending tasks=
(3) [ZoneTask, ZoneTask, ZoneTask]
0: ZoneTask
callback: ƒ ()
cancelFn: undefined
creationLocation: Error: Task 'macroTask' from 'setTimeout'. at TaskTrackingZoneSpec.push.FGvd.TaskTrackingZoneSpec.onScheduleTask (http://localhost:4200/vendor.js:54102:40) at ZoneDelegate.scheduleTask (http://localhost:4200/polyfills.js:9471:55) at Object.onScheduleTask (http://localhost:4200/polyfills.js:9365:69) at ZoneDelegate.scheduleTask (http://localhost:4200/polyfills.js:9471:55) at Zone.scheduleTask (http://localhost:4200/polyfills.js:9303:47) at Zone.scheduleMacroTask (http://localhost:4200/polyfills.js:9326:29) at scheduleMacroTaskWithCurrentZone (http://localhost:4200/polyfills.js:10227:29) at http://localhost:4200/polyfills.js:11679:34 at proto.<computed> (http://localhost:4200/polyfills.js:10542:52) at loop_1 (http://localhost:4200/vendor.js:23731:42)
data: {isPeriodic: false, delay: 1000, args: Arguments(2), handleId: 1516}
invoke: ƒ ()
runCount: 0
scheduleFn: ƒ scheduleTask(task)
source: "setTimeout"
type: "macroTask"
_state: "notScheduled"
_zone: Zone {_parent: Zone, _name: "angular", _properties: {…}, _zoneDelegate: ZoneDelegate}
_zoneDelegates: null
state: (...)
zone: (...)
__proto__: Object
1: ZoneTask {_zone: Zone, runCount: 0, _zoneDelegates: null, _state: "notScheduled", type: "macroTask", …}
2: ZoneTask {_zone: Zone, runCount: 0, _zoneDelegates: null, _state: "notScheduled", type: "macroTask", …}
length: 3
__proto__: Array(0)
UPDATE!
I can avoid this problem with a tiny workaround.
Need to create a function that using runOutsideAngular(), and if I create the chart inside the callback, no will be running macrotasks!
constructor(#Inject(PLATFORM_ID) private platformId, private zone: NgZone) {
}
// Run the function only in the browser
browserOnly(f: () => void): void {
if (isPlatformBrowser(this.platformId)) {
this.zone.runOutsideAngular(() => {
f();
});
}
}
ngOnInit(): void {
this.browserOnly(() => {
this.chart = am4core.create('line-chart-placeholder', am4charts.XYChart);
});
}
yes, you can ignore it. You need to disable main protractor's feature that waits for page to be ready, like this
await browser.waitForAngularEnabled(false)
for more info, read here

JOI validation when condition not working as expected

I have the following JOI schema defined;
schema = Joi.object({
flag: Joi.boolean()
.required(),
toolDetail: Joi.array().items(
Joi.object({
amount: Joi.number()
.min(0)
.max(499.99)
.precision(2)
.options({ convert: false })
.when('flag', {
is: true,
then: Joi.number().required(),
otherwise: Joi.number()
.strip()
.optional()
.allow(''),
}),
tool: Joi.string()
.min(0)
.max(500)
.when('flag', {
is: true,
then: Joi.string().required(),
otherwise: Joi.string()
.strip()
.optional()
.allow(''),
}),
}),
),
});
I have confirmed that the flag is being set correctly, but it seems that 'amount' and 'tool' is always hitting the otherwise condition, regardless of the value set in the 'flag'.
Is there something incorrect in my definition?
Works as expected once I added 4 dots prefix to the flag
.when('....flag', {
https://joi.dev/api/?v=17.2.1#relative-references

mailchimp3 (Python-mailchimp-api) How to set tags

I tried:
client.lists.members.create('1111111', {
'email_address' : 'frogger116#gmail.com',
'status' : 'subscribed',
"tags": [{'name': 'frogger', 'status' : 'active'}],
})
and get:
mailchimp3.mailchimpclient.MailChimpError: {
'type': 'http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/',
'title': 'Invalid Resource',
'status': 400,
'detail': 'Expected argument of type "string", "stdClass" given',
'instance': '5ae1b966-ed35-49f1-ad32-0a39c3d63593'
}
Without the "tags" line the satement works
This works for me (you need hash the email address)
hash = get_subscriber_hash(email_address)
data = {
'tags': [
{'name': 'foo', 'status': 'active'},
{'name': 'bar', 'status': 'inactive'}
]
}
client.lists.members.tags.update(list_id=list_id, subscriber_hash=hash, data=data)
I think in the latest version the tags are just strings. At least, this is what I use.
client.lists.members.create('1111111', {
'email_address' : 'frogger116#gmail.com',
'status' : 'subscribed',
'tags': ['frogger','invaders']
})
Also, to be certain, make sure tags exist in the system. Especially if doing an update rather than insert. Its not super consistant about dealing with unknown tags.
Also of course, make sure the '1111111' audience id exists.
SUPPLEMENTAL CODE
Of course, I've found a better way to ensure what you want is to use other methods to add to tags rather than on insert. You may have to tweak the below functions as they are part of a class, but they should give you other ideas on how to add and remove tags from users
def bulkUpdateTagNamesForEmails(self, emailsToUpdate, tagNames, remove=False):
audienceId = self.audienceId
if remove:
data = {'members_to_remove':emailsToUpdate}
else:
data = {'members_to_add':emailsToUpdate}
segments = None
for tagName in tagNames:
segId,segments = self.getSegmentIdFromTagName(tagName,segments)
if segId:
self.brResponse = self.mcClient.lists.segments.update_members(list_id=audienceId, segment_id=segId, data=data)
def createTagNameIfNeeded(self, tagName):
audienceId = self.audienceId
# Check for tag name
found = False
segments = self.mcClient.lists.segments.all(list_id=audienceId, get_all=False)
for segment in segments['segments']:
if segment['name'] == tagName:
found = True
print("Found tag")
# If not found, create it
if not found:
print(f"Creating new tag {tagName}")
data = {'name': tagName,'static_segment': []}
self.mcClient.lists.segments.create(list_id=audienceId, data=data)
def getSegmentIdFromTagName(self,reqTagName,segments=None):
audienceId = self.audienceId
reqId = None
if not segments:
segments = self.mcClient.lists.segments.all(list_id=audienceId, get_all=True)
for segment in segments['segments']:
segName = segment['name']
segId = segment['id']
if segName == reqTagName:
reqId = segId
break
return reqId,segments

ER_TOO_LONG_KEY in SailsJS 1.0 with sails-mysql

I got this error with sails when I try to sails lift:
info: ·• Auto-migrating... (drop)
error: A hook (`orm`) failed to load!
error:
error: Error: ER_TOO_LONG_KEY: Specified key was too long; max key length is 767 bytes
I just have one model for now: 
module.exports = {
datastore: 'default',
tableName: 'sci_user',
attributes: {
email: {
type: 'string',
required: true,
unique: true
},
password: {
type: 'string',
required: true
}
}
It's really simple and I got it from the documentation. I don't understand. It seems it's because of the unique: true.
This is due to a combination of factors, but the most pertinent one is that sails-mysql currently defaults to using the utf8mb4 character set for string attributes, to allow the use of emojis and other extended characters. We're working on a patch to make this configurable rather than the default, but in the meantime the quickest workaround is to declare the columnType for your attributes directly:
module.exports = {
datastore: 'default',
tableName: 'sci_user',
attributes: {
email: {
type: 'string',
required: true,
unique: true,
columnType: 'varchar'
},
password: {
type: 'string',
required: true,
columnType: 'varchar'
}
}

How to send a boolean to python-eve?

I'm trying to update a boolean value using python eve, but I always receive the same error,
_issues: {deleted:must be of boolean type}
deleted: "must be of boolean type"
_status: "ERR"
I've tried sending the field as true (setting javascript type) 'True' and 'true' (as text) and 1, but the error is always the same.
startdate=2014-03-25T03%3A00%3A00.000Z&code=dsa&enddate=2014-03-31T03%3A00%3A00.000Z&name=sad&note=&deleted=True
startdate=2014-03-25T03%3A00%3A00.000Z&code=dsa&enddate=2014-03-31T03%3A00%3A00.000Z&name=sad&note=&deleted=true
startdate=2014-03-25T03%3A00%3A00.000Z&code=dsa&enddate=2014-03-31T03%3A00%3A00.000Z&name=sad&note=&deleted=1
Any idea?
Regards
Gaston
settings.py
entity= {
'resource_methods': ['GET', 'POST'],
'schema': schema,
'datasource': {
'filter': {'$or':[{'deleted':{'$exists':0}},{'deleted':False}]}
}
}
schema = {
'name': {
'type': 'string',
'minlength': 1,
'maxlength': 50,
'required': True,
},
'code': {
'type': 'string',
},
'deleted':{
'type':'boolean',
'default':False
}
}
Full Request
Request URL:http://localhost:5000/campaign/532f797da54d75faabdb25d5
Request Method:PUT
Status Code:200 OK
Request Headersview source
Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,no;q=0.6,es;q=0.4
Cache-Control:no-cache
Connection:keep-alive
Content-Length:112
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Host:localhost:5000
If-Match:3c7bc93e3c7d60da62f350ac990c16e29b08660f
Origin:http://localhost:5000
Pragma:no-cache
Referer:http://localhost:5000/static/index.html
X-Requested-With:XMLHttpRequest
Form Dataview parsed
startdate=2014-03-25T03%3A00%3A00.000Z&code=dsa&enddate=2014-03-31T03%3A00%3A00.000Z&name=sad&note=&deleted=True
Response Headersview source
Access-Control-Allow-Headers:
Access-Control-Allow-Max-Age:21600
Access-Control-Allow-Methods:HEAD, GET, PUT, POST, DELETE, OPTIONS, PATCH
Access-Control-Allow-Origin:*
Content-Length:69
Content-Type:application/json
Date:Mon, 24 Mar 2014 00:30:10 GMT
Server:Werkzeug/0.9.4 Python/2.7.5
Set-Cookie:session=eyJfcGVybWFuZW50Ijp0cn
If you change your schema to coerce deleted value to bool, you can send int or str values and have it converted to bool on insert/update
First, create a function to convert whatever comes, to bool:
to_bool = lambda v: v if type(v) is bool else str(v).lower() in ['true', '1']
Then, change the deleted in the schema to use the function to coerce values, like this:
'deleted':{
'type':'boolean',
'coerce': to_bool,
'default':False
}
With this, you can per example send deleted with values such as '0', 0, 'false' or 'False' yelding to boolean false, or '1', 1, 'true' or 'True' resulting in true
This happens only when you send the request in the content type of form-data or application/x-www-form-urlencoded. In case of AJAX requests, sending boolean value works.
var payload = {
"deleted": false
};
var xhr = $.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(payload),
dataType: "json",
url: "some url"
})
Your payload should be a dict like:
payload = {"somebool": False}
then you convert it to a json string:
payload_json = json.dumps(payload)
which results in a lowercased bool value in a string:
'{"f5only": false}'
then you shoulc be able to post or patch it:
requests.post("{0}/endpoint/".format(api_server), headers=headers, data=payload_json)