I have this problem with my code. When Iinsert three or more params in the body request, I get this Error "POST Error: or_ expected 2 arguments, got 3."
I can only pass one or two parameters in the body, in this case it works fine. But I don't understand where is the mistake. Can someone help me?
def read_uptime(logid, filteredData, dateStart, dateEnd, timeStart, timeEnd, elementsForPage, currentPage, filterUptime):
log.info(f"{logid} read_uptime: Started")
try:
# Check Timeframe Correct
startDateTime, endDateTime = _checkDataInput(timeStart, timeEnd, dateStart, dateEnd)
# Create Filter
filters = _createFilter(filteredData, startDateTime, endDateTime, filterUptime)
# Query
dataFiltered = uptime_model_db.query.with_entities(
uptime_model_db.projectId.label('projectId'),
uptime_model_db.url.label('url'),
uptime_model_db.timeStamp.label('timeStamp'),
uptime_model_db.uptime.label('uptime'),
uptime_model_db.latency.label('latency')
).filter(*filters).paginate(per_page=int(elementsForPage + 1), page=int(currentPage), error_out=True)
# Checking more pages
nextPage = {
"currentPage": currentPage,
"totalElements": len(dataFiltered.items)
}
if (len(dataFiltered.items) > elementsForPage):
nextPage["nextPage"] = True
else:
nextPage["nextPage"] = False
# Format and return JSON
return _createJson(dataFiltered.items, nextPage)
except Exception as e:
log.error(f"{logid} read_uptime: function read_uptime returned {e}")
raise e
i get in this code the mistake: "array.Filter.append(and_(uptime_model.db.porjectId == projectId, or_(*arrayUrl))"
def filterAppend(arrayFilter, urls, projectId, arrayUrl):
if(len(urls) == 1):
arrayFilter.append(and_(uptime_model_db.projectId == projectId, uptime_model_db.url == urls[0]))
if(len(urls) > 1):
for url in urls:
arrayUrl.append(uptime_model_db.url == url)
arrayFilter.append(and_(uptime_model_db.projectId == projectId, or_(*arrayUrl)))
i get in this code the mistake:
"filters.append(or_(*arrayFilter))"
def _createFilter(filteredData, startDateTime, endDateTime, filterUptime):
filters = []
if filteredData is not None:
arrayFilter = []
for data in filteredData:
projectId = data["projectId"]
urls = data["uptimeUrls"]
arrayUrl = []
if (len(filteredData) == 1):
filterAppend(filters, urls, projectId, arrayUrl)
else:
filterAppend(arrayFilter, urls, projectId, arrayUrl)
if(len(filteredData) > 1 or len(arrayFilter) > 1):
filters.append(or_(*arrayFilter))
if startDateTime is not None:
filters.append(str(startDateTime) <= uptime_model_db.timeStamp)
if startDateTime is not None:
filters.append(str(endDateTime) >= uptime_model_db.timeStamp)
if filterUptime == "True":
filters.append(uptime_model_db.uptime < 100)
return filters
import or_ from sqlalchemy instead of operators:
from sqlalchemy import or_
Related
I am trying to build a command in python for Maya following a course on youtube and it's showing this error "# Error: RuntimeError: file line 2: AttributeError: file C:/Users/saeed/OneDrive/Documents/maya/2020/Plugins/vertexParticle.py line 23: 'module' object has no attribute 'MStatus' # "
I checked Maya API documents and we should have "MStatus" class but I have no idea why it's not accepted, I tried to use "MStatusCode" and it's showing same error.
from maya import OpenMaya
from maya import OpenMayaMPx
from maya import OpenMayaFX
import sys
commandName = "vertexParticle"
kHelpFlag = "-h"
kHelpLongFlag = "-help"
kSparseFlag = "-s"
kSparseLongFlag = "-sparse"
helpMessage = "This command will attach a particle for each vertex"
class pluginCommand(OpenMayaMPx.MPxCommand):
sparse = None
def __init__(self):
OpenMayaMPx.MPxCommand.__init__(self)
def argumentParser(self, argList):
syntax = self.syntax()
parserArguments = OpenMaya.MArgDatabase(syntax, argList)
if parserArguments.isFlagSet(kSparseFlag):
self.sparse = parserArguments.flagArgumentDouble(kSparseFlag, 0)
return OpenMaya.MStatus.kSuccess
if parserArguments.isFlagSet(kSparseLongFlag):
self.sparse = parserArguments.flagArgumentDouble(kSparseLongFlag, 0)
return OpenMaya.MStatus.kSuccess
if parserArguments.isFlagSet(kHelpFlag):
self.setResult(helpMessage)
return OpenMaya.MStatus.kSuccess
if parserArguments.isFlagSet(kHelpLongFlag):
self.setResult(helpMessage)
return OpenMaya.MStatus.kSuccess
def isUndoable(self):
return True
def undoIt(self):
print "undo"
mFnDagNode = OpenMaya.MFnDagNode(self.mObjParticle)
mDagMod = OpenMaya.MDagModifier()
mDagMod.deleteNode(mFnDagNode.parent(0))
mDagMod.doIt()
return OpenMaya.MStatus.kSuccess
def redoIt(self):
mSel = OpenMaya.MSelectionList()
mDagPath = OpenMaya.MDagPath()
mFnMesh = OpenMaya.MFnMesh()
OpenMaya.MGlobal.getActiveSelectionList(mSel)
if mSel.length() >= 1:
try:
mSel.getDagPath(0, mDagPath)
mFnMesh.setObject(mDagPath)
except:
print "please select a poly mesh"
return OpenMaya.MStatus.kUnknownParameter
else:
print "please select a poly mesh"
return OpenMaya.MStatus.kUnknownParameter
mPointArray = OpenMaya.MPointArray()
mFnMesh.getPoints(mPointArray, OpenMaya.MSpace.kWorld)
mFnParticle = OpenMayaFX.MFnParticleSystem()
self.mObjParticle = mFnParticle.create()
mFnParticle = OpenMayaFX.MFnParticleSystem(self.mObjParticle)
counter == 0
for i in xrange(mPointArray.length()):
if i%self.sparse == 0:
mFnParticle.emit(mPointArray[i])
counter += 1
print "total points :" + str(counter)
mFnParticle.saveInitialState()
return OpenMaya.MStatus.kSuccess
def doIt(self, argList):
self.argumentParser(argList)
if self.sparse != None:
self.redoIt()
return OpenMaya.MStatus.kSuccess
def cmdCreator():
return OpenMayaMPx.asMPxPtr(pluginCommand())
def syntaxCreator():
syntax = OpenMaya.MSyntax()
syntax.addFlag(kHelpFlag, kHelpLongFlag)
syntax.addFlag(kSparseFlag, kSparseLongFlag, OpenMaya.MSyntax.kDouble)
return syntax
def initializePlugin(mObject):
mPlugin = OpenMayaMPx.MFnPlugin(mObject)
try:
mPlugin.registerCommand(commandName, cmdCreator, syntaxCreator)
except:
sys.stderr.write("Failed to register" + commandName)
def uninitializePlugin(mObject):
mPlugin = OpenMayaMPx.MFnPlugin(pluginCommand())
try:
mPlugin.deregisterCommand(commandName)
except:
sys.stderr.write("Failed to deregister" + commandName)
Because MStatus.MStatusCode is an enum, you can return its integer value in Python. The only issue is that because in C++ this is an enum, there is no guarantee that the values won't change/shift between releases. This enum has remained consistent since 2019, so there isn't much risk of this happening for MStatus.MStatusCode.
https://help.autodesk.com/view/MAYAUL/2019/ENU/?guid=__cpp_ref_class_m_status_html
https://help.autodesk.com/view/MAYAUL/2023/ENU/?guid=Maya_SDK_cpp_ref_class_m_status_html
Somewhere in the top of your file simply add the constants you intend to use:
MStatus_kSuccess = 0
MStatus_kFailure = 1
MStatus_kUnknownParameter = 5
Then return the constant instead in your functions:
if parserArguments.isFlagSet(kHelpFlag):
self.setResult(helpMessage)
return MStatus_kSuccess
lista =
[{Identity: joe,
summary:[
{distance: 1, time:2, status: idle},
{distance:2, time:5, status: moving}],
{unit: imperial}]
I can pull the data easily and put in pandas. The issue is, if an identity has multiple instances of, say idle, it takes the last value, instead of summing together.
my code...
zdrivershours = {}
zdistance = {}
zstophours = {}
For driver in resp:
driverid[driver['AssetID']] = driver['AssetName']
for value in [driver['SegmentSummary']]:
for value in value:
if value['SegmentType'] == 'Motion':
zdriverhours[driver['AssetID']] = round(value['Time']/3600,2)
if value['SegmentType'] == 'Stop':
zstophours[driver['AssetID']] = round(value['IdleTime']/3600,2)
zdistance[driver['AssetID']] = value['Distance']
To obtain the summatory of distance for every driver replace:
zdistance[driver['AssetID']] = value['Distance']
by
if driver['AssetID'] in zdistance:
zdistance[driver['AssetID']] = zdistance[driver['AssetID']] + value['Distance']
else:
zdistance[driver['AssetID']] = value['Distance']
I'd like to do a and clause with two lists of multiple or clauses from the same table.
The problem with the following code is, that the query result is empty. If I just select 'indices' or 'brokers', the result is fine.
...
query = query.join(StockGroupTicker, on=(Ticker.id == StockGroupTicker.ticker))
# indices
if "indices" in filter:
where_indices = []
for f in filter["indices"]:
where_indices.append(StockGroupTicker.stock_index == int(f))
if len(where_indices):
query = query.where(peewee.reduce(peewee.operator.or_, where_indices))
# broker
if "brokers" in filter:
where_broker = []
for f in filter["brokers"]:
where_broker.append(StockGroupTicker.stock_index == int(f))
if len(where_broker):
query = query.where(peewee.reduce(peewee.operator.or_, where_broker))
return query.distinct()
SQL Querie (update)
# index and brocker
SELECT
DISTINCT `t1`.`id`,
`t1`.`symbol`,
`t1`.`type`,
`t1`.`name`,
`t1`.`sector`,
`t1`.`region`,
`t1`.`primary_exchange`,
`t1`.`currency`,
`t1`.`score`,
`t1`.`last_price`,
`t1`.`last_price_date`,
`t1`.`last_price_check`,
`t1`.`last_stock_split`,
`t1`.`next_earning`,
`t1`.`last_earnings_update`,
`t1`.`disused`,
`t1`.`source`,
`t1`.`source_intraday`,
`t1`.`created`,
`t1`.`modified`,
`t2`.`invest_score` AS `invest_score`
FROM
`ticker` AS `t1`
INNER JOIN `tickerstats` AS `t2` ON
(`t1`.`id` = `t2`.`ticker_id`)
INNER JOIN `stockgroupticker` AS `t3` ON
(`t1`.`id` = `t3`.`ticker_id`)
WHERE
(((((`t1`.`disused` IS NULL)
OR (`t1`.`disused` = 0))
AND (`t2`.`volume_mean_5` > 10000.0))
AND (`t3`.`stock_index_id` = 1))
AND (`t3`.`stock_index_id` = 10)
)
Thanks to #coleifer, the peewee solution is quite simple. I had to use an alias.
if "indices" in filter and filter["indices"]:
query = query.join(
StockGroupTicker, peewee.JOIN.INNER, on=(Ticker.id == StockGroupTicker.ticker)
)
where_indices = []
for f in filter["indices"]:
where_indices.append(StockGroupTicker.stock_index == int(f))
if len(where_indices):
query = query.where(peewee.reduce(peewee.operator.or_, where_indices))
if "brokers" in filter and filter["brokers"]:
BrokerGroupTicker = StockGroupTicker.alias()
query = query.join(
BrokerGroupTicker, peewee.JOIN.INNER, on=(Ticker.id == BrokerGroupTicker.ticker)
)
where_broker = []
for f in filter["brokers"]:
where_broker.append(BrokerGroupTicker.stock_index == int(f))
if len(where_broker):
query = query.where(peewee.reduce(peewee.operator.or_, where_broker))
return query.distinct()
Google Custom API search code I wrote
import time
from googleapiclient.discovery import build
# Google custom search API info
API_KEY = 'My Key'
API_ID = 'My ID'
def spider_next_page(service, index, searchterm_in, incl_searchterm_in, sitesearch_in):
time.sleep(1)
response = service.cse().list(
q=searchterm_in,
orTerms=incl_searchterm_in,
siteSearch=sitesearch_in,
cx=my_cse_id,
num=10,
start=index,
).execute()
nextPageIndex = response['queries']['nextPage'][0]['startIndex']
nextPageCount = response['queries']['nextPage'][0]['count']
for values_spider_next_page in response['items']:
itemsave.append(values_spider_next_page)
if nextPageIndex == 21:
pageno = ((nextPageIndex - 1) / 10)
print('Found', round(pageno), "Pages")
return
if nextPageCount != 0:
spider_next_page(service, nextPageIndex, searchterm_in, incl_searchterm_in, sitesearch_in)
def spider(searchterm_in, incl_searchterm_in, sitesearch_in):
service = build("customsearch", "v1",
developerKey=my_api_key)
res = service.cse().list(
q=searchterm_in,
orTerms=incl_searchterm_in,
siteSearch=sitesearch_in,
cx=my_cse_id,
).execute()
searchterm_in = res['queries']['request'][0]['searchTerms']
nextPageIndex = res['queries']['nextPage'][0]['startIndex']
nextPageCount = res['queries']['nextPage'][0]['count']
print('nextPageIndex', nextPageIndex)
print("Search Query:", searchterm_in)
print("Include Query :", incl_searchterm_in)
print("Target Site :", sitesearch_in)
for values_spider in res['items']:
itemsave.append(values_spider)
if nextPageCount != 0:
spider_next_page(service, nextPageIndex, searchterm_in, incl_searchterm_in, sitesearch_in)
return
if __name__ == '__main__':
my_api_key = API_KEY
my_cse_id = API_ID
itemsave = []
spider('men shorts', 'adidas', 'yahoo.com')
Normally, data can be obtained without errors, but sometimes the errors below occur.
Traceback (most recent call last):
File "D://Google_Search_API_0.4.py", line 122, in <module>
spider(f'{searchterm}', f'{incl_searchterm}', f'{sitesearch}')
File "D://Google_Search_API_0.4.py", line 70, in spider
nextPageIndex = res['queries']['nextPage'][0]['startIndex']
KeyError: 'nextPage'
It works in the following order.
spider('men shorts', 'adidas', 'yahoo.com') # input query (q,orTerms,siteSearch)
spider(searchterm_in, incl_searchterm_in, sitesearch_in): # first page -> get input query
spider_next_page(service, index, searchterm_in, incl_searchterm_in, sitesearch_in): # next page
If an error occurs, it occurs here.
def spider(searchterm_in, incl_searchterm_in, sitesearch_in):
...
--> nextPageIndex = res['queries']['nextPage'][0]['startIndex']
If I'm right, what's the problem? And why does it sometimes work without errors?
Maybe it is the end of data so there is no more nextPage.
You could use try/except to catch error and skip code.
Or you should run it in if 'nextPage' in res['queries']:
if 'nextPage' not in res['queries']:`
print("The End")
else:
nextPageIndex = response['queries']['nextPage'][0]['startIndex']
nextPageCount = response['queries']['nextPage'][0]['count']
for values_spider_next_page in response['items']:
itemsave.append(values_spider_next_page)
if nextPageIndex == 21:
pageno = ((nextPageIndex - 1) / 10)
print('Found', round(pageno), "Pages")
return
if nextPageCount != 0:
spider_next_page(service, nextPageIndex, searchterm_in, incl_searchterm_in, sitesearch_in)
I'm working on a site built in django, but i'm having a little trouble, in multiple parts im getting double (sometimes 3 or 4) post, for example im submitting a form where you need to save a contact, but when the page reloads im getting 2, 3 or 4 of the same contact. The difference in time is about 0.5 secs. of each other.
I tried to code a little solution like this:
def not_double_post(request):
session_data = request.session.get('post_data', None)
session_new_data = '-'.join([str(request.user.username),
str(int(time.time()))])
if session_data is None:
request.session['post_data'] = session_new_data
return True
else:
current_user = request.user.username
current_time = int(time.time())
session_post_user = session_data.split('-')[0]
session_post_time = session_data.split('-')[1]
if current_user == session_post_user:
time_difference = current_time - int(session_post_time)
if time_difference > 10:
request.session.pop('post_data')
request.session['post_data'] = ''.join([str(current_user),
str(int(time.time()))])
return True
else:
return False
else:
return True
On each request.method == 'POST' i check this function, store the user and time when the operation has made in session, if the operation user are the same, and the time difference is less than 10 seconds, is an invalid post.
(I'm also setting the attribute of the button to disabled when the user clicks)
But im getting double post with this. I dont know if this really works like i expect, but it would be good to take another point of view (or another recommendation to achieve this).
Thanks!
==== UDATE views.py =====
def cancel_invoice(request, pk):
if not_double_post(request):
order = PaymentOrder.objects.get(pk=pk)
order.cancelled_date = datetime.date.today()
folio = order.invoice_sat.comp_folio
serie = order.invoice_sat.comp_serie
rfc_receptor = order.client.rfc
folio = folio
soap_doc = '<soapenv:Envelope ' \
'xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" ' \
'xmlns:xsaf="http://xsafilereceiver.webservices.manager.xsa.tralix.com">' \
'<soapenv:Header/>' \
'<soapenv:Body>' \
'<xsaf:cancelaCFD>' \
'<xsaf:in0>' + serie + '</xsaf:in0>' \
'<xsaf:in1>' + folio + '</xsaf:in1>' \
'<xsaf:in2>' + settings.IENTC_RFC + '</xsaf:in2>' \
'<xsaf:in3>' + settings.API_KEY + '</xsaf:in3>' \
'</xsaf:cancelaCFD>' \
'</soapenv:Body>' \
'</soapenv:Envelope>'
factura_client = ServiceClient(settings.API_CANCEL_URL)
invoice_status = factura_client.service.cancelaCFD(__inject={'msg': soap_doc})
if invoice_status:
order.invoice_sat.invoice_status = 0
order.amount_to_pay = None
order.invoice_sat.save()
order.save()
if serie == settings.INVOICE_SERIE:
order.client.balance = order.client.balance + order.total
else:
order.client.balance = order.client.balance - order.total
order.client.save()
comment = request.POST.get('comment', None)
if comment.strip() != '' and comment is not None:
cancelled_folio = folio
CANCEL_EVENT = 'Administración'
CANCEL_INVOICE_TITLE = 'Cancelación de Factura #%s' % \
str(cancelled_folio)
cancel_type, created = EventType.objects.get_or_create(
name=CANCEL_EVENT)
Event(
client=order.client,
register_date=datetime.datetime.now(),
event_type=cancel_type,
event=CANCEL_INVOICE_TITLE,
additional_comments=comment.strip(),
created_by=request.user
).save()
mandrill_client = mandrill.Mandrill(settings.MADRILL_API_KEY)
message = dict()
message['subject'] = 'Cancelación de Factura'
message['from_email'] = 'crm#ientc.com'
message['from_name'] = 'CRM IENTC'
message['text'] = CANCEL_INVOICE_TITLE
message['to'] = [
{
'email': 'conta#ientc.com',
'name': 'Contabilidad IENTC',
'type': 'to'
}
]
result = mandrill_client.messages.send(
message=message, async=False)
print result
return response_json("OK", 200)
else:
return response_json("ERROR CANCELANDO FACTURA", 400)
else:
return response_json("OK", 200)
In this particular POST im making a soap call, but also i'm having troubles on other POST with simple code. Thanks!