I encounter an error 405 during a PUT request.
I have a list of ids ids = [1, 2, 3, 4] and my goal is to update two field activated_at and updated_at with the current date time.
query.py
--------
async def validate(ids: list) -> Array:
"""Validates a list of FDES in the database"""
# Preparing the updates
updates = {
"updated_at": datetime.now(),
"validated_at": datetime.now()
}
# Making the updates
await db.fdeses.updateMany({"id": {"$in": ids}}, {"$set": updates})
# Returning the modified document
documents = await db.fdeses.find({"id": {"$in": ids}}).to_list(CURSOR_LIMIT)
return documents
controllers.py
--------------
async def validate(ids:list) -> Fdeses:
db_fdeses = await queries.fdes.validate(ids)
return db_fdeses
router.py
---------
#router.put("/admin/fdes/activate", response_model=Fdeses)
async def validate(ids:list = Body(...))->Fdeses:
response = await controllers.fdes.validate(ids)
return response
I don't understand what is wrong with my code. What 405 error exactly mean?
EDIT:
I tried a PUT method using Postman instead of my VueJS client and I have an error 500.
Why my backend return me errors on other functions than functions I use for this endpoint? In this case it returns me errors about PUT function for /admin/fdes and GET function for admin/fdes.
Here is the error on FastAPI:
INFO: 172.20.0.1:65334 - "PUT /admin/fdes/activate HTTP/1.1" 500 Internal Server Error
File "./app/routers/fdes.py", line 40, in put_fdes
response = await controllers.fdes.update_fdes(fdes_id, fdes)
File "./app/controllers/fdes.py", line 57, in update_fdes
db_fdes = await queries.fdes.select_fdes(fdes_id)
File "./app/models/queries/fdes.py", line 16, in select_fdes
fdes_id = ObjectId(fdes_id)
File "/usr/local/lib/python3.8/site-packages/bson/objectid.py", line 110, in __init__
self.__validate(oid)
File "/usr/local/lib/python3.8/site-packages/bson/objectid.py", line 213, in __validate
_raise_invalid_id(oid)
File "/usr/local/lib/python3.8/site-packages/bson/objectid.py", line 38, in _raise_invalid_id
raise InvalidId(
bson.errors.InvalidId: 'activate' is not a valid ObjectId, it must be a 12-byte input or a 24-character hex string
Related
I am getting this error when trying to implement the Document OCR from google cloud in python as explained here: https://cloud.google.com/document-ai/docs/ocr
When I run
result = client.process_document(request=request)
I get this error
Traceback (most recent call last):
File "/Users/Niolo/Desktop/untitled/Desktop/lib/python3.8/site-packages/google/api_core/grpc_helpers.py", line 73, in error_remapped_callable
return callable_(*args, **kwargs)
File "/Users/Niolo/Desktop/untitled/Desktop/lib/python3.8/site-packages/grpc/_channel.py", line 923, in __call__
return _end_unary_response_blocking(state, call, False, None)
File "/Users/Niolo/Desktop/untitled/Desktop/lib/python3.8/site-packages/grpc/_channel.py", line 826, in _end_unary_response_blocking
raise _InactiveRpcError(state)
grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
status = StatusCode.INVALID_ARGUMENT
details = "Request contains an invalid argument."
debug_error_string = "{"created":"#1614769280.332675000","description":"Error received from peer ipv4:142.250.180.138:443","file":"src/core/lib/surface/call.cc","file_line":1068,"grpc_message":"Request contains an invalid argument.","grpc_status":3}"
>
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/Users/Niolo/Desktop/untitled/Desktop/lib/python3.8/site-packages/google/cloud/documentai_v1beta3/services/document_processor_service/client.py", line 327, in process_document
response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
File "/Users/Niolo/Desktop/untitled/Desktop/lib/python3.8/site-packages/google/api_core/gapic_v1/method.py", line 145, in __call__
return wrapped_func(*args, **kwargs)
File "/Users/Niolo/Desktop/untitled/Desktop/lib/python3.8/site-packages/google/api_core/retry.py", line 281, in retry_wrapped_func
return retry_target(
File "/Users/Niolo/Desktop/untitled/Desktop/lib/python3.8/site-packages/google/api_core/retry.py", line 184, in retry_target
return target()
File "/Users/Niolo/Desktop/untitled/Desktop/lib/python3.8/site-packages/google/api_core/grpc_helpers.py", line 75, in error_remapped_callable
six.raise_from(exceptions.from_grpc_error(exc), exc)
File "<string>", line 3, in raise_from
google.api_core.exceptions.InvalidArgument: 400 Request contains an invalid argument.
My full code:
import os
# Import the base64 encoding library.
project_id= 'your-project-id'
location = 'eu' # Format is 'us' or 'eu'
processor_id = 'your-processor-id' # Create processor in Cloud Console
file_path = '/file_path/invoice.pdf'
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/full_path/your_credentials.json"
def process_document_sample(
project_id: str, location: str, processor_id: str, file_path: str
):
from google.cloud import documentai_v1beta3 as documentai
# Instantiates a client
client = documentai.DocumentProcessorServiceClient()
# The full resource name of the processor, e.g.:
# projects/project-id/locations/location/processor/processor-id
# You must create new processors in the Cloud Console first
name = f"projects/{project_id}/locations/{location}/processors/{processor_id}"
with open(file_path, "rb") as image:
image_content = image.read()
# Read the file into memory
document = {"content": image_content, "mime_type": "application/pdf"}
# Configure the process request
request = {"name": name, "document": document}
# Recognizes text entities in the PDF document
result = client.process_document(request=request)
document = result.document
print("Document processing complete.")
# For a full list of Document object attributes, please reference this page: https://googleapis.dev/python/documentai/latest/_modules/google/cloud/documentai_v1beta3/types/document.html#Document
document_pages = document.pages
# Read the text recognition output from the processor
print("The document contains the following paragraphs:")
for page in document_pages:
paragraphs = page.paragraphs
for paragraph in paragraphs:
paragraph_text = get_text(paragraph.layout, document)
print(f"Paragraph text: {paragraph_text}")
client = documentai.DocumentProcessorServiceClient() points to US end point by default.
in: client = documentai.DocumentProcessorServiceClient()
in: print(client.DEFAULT_ENDPOINT)
out: us-documentai.googleapis.com
You need to override the api_endpoint to EU for this to work.
from google.api_core.client_options import ClientOptions
# Set endpoint to EU
options = ClientOptions(api_endpoint="eu-documentai.googleapis.com:443")
# Instantiates a client
client = documentai.DocumentProcessorServiceClient(client_options=options)
Here is the full code:
import os
# TODO(developer): Uncomment these variables before running the sample.
project_id= 'your-project-id'
location = 'eu' # Format is 'us' or 'eu'
processor_id = 'your-processor-id' # Create processor in Cloud Console
file_path = '/file_path/invoice.pdf'
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/full_path/your_credentials.json"
def process_document_sample(
project_id: str, location: str, processor_id: str, file_path: str
):
from google.cloud import documentai_v1beta3 as documentai
from google.api_core.client_options import ClientOptions
# Set endpoint to EU
options = ClientOptions(api_endpoint="eu-documentai.googleapis.com:443")
# Instantiates a client
client = documentai.DocumentProcessorServiceClient(client_options=options)
# The full resource name of the processor, e.g.:
# projects/project-id/locations/location/processor/processor-id
# You must create new processors in the Cloud Console first
name = f"projects/{project_id}/locations/{location}/processors/{processor_id}"
with open(file_path, "rb") as image:
image_content = image.read()
# Read the file into memory
document = {"content": image_content, "mime_type": "application/pdf"}
# Configure the process request
request = {"name": name, "document": document}
# Recognizes text entities in the PDF document
result = client.process_document(request=request)
document = result.document
print("Document processing complete.")
# For a full list of Document object attributes, please reference this page: https://googleapis.dev/python/documentai/latest/_modules/google/cloud/documentai_v1beta3/types/document.html#Document
document_pages = document.pages
# Read the text recognition output from the processor
print("The document contains the following paragraphs:")
for page in document_pages:
paragraphs = page.paragraphs
for paragraph in paragraphs:
paragraph_text = get_text(paragraph.layout, document)
print(f"Paragraph text: {paragraph_text}")
Here is a snippet of the output:
I have a python script which allows me to check if a number is used on telegram or not.
I try to change the variable "phone_number" to a .txt list which basically contain phone number (There is one phone number per line)
I want the script to take a phone number from the file.txt check if it exists or not then move on to the next one and so on until all the numbers are checked.
This is what i try so far...
import random
from telethon import TelegramClient
from telethon import functions, types
import ast
api_id = XXXXX
api_hash = 'XXXXXXXXXXXXXXXXXX'
client = TelegramClient('session', api_id, api_hash)
async def main():
phone_in = []
with open('file.txt', 'r') as f:
phone_str = f.readline()
phone_in.append(ast.literal_eval(phone_str))
result = await client(functions.contacts.ImportContactsRequest(
contacts=[types.InputPhoneContact(
client_id=random.randrange(-2**63, 2**63),
phone=phone_in,
first_name='Some Name',
last_name=''
)]
))
if len(result.users):
print(f"{phone_in} has a telegram account")
await client(functions.contacts.DeleteContactsRequest(result.users))
else:
print(f"couldn't find an account for {phone_in}")
client.start()
client.loop.run_until_complete(main())
I tried this but I had an error which is the following :
Traceback (most recent call last):
File "/Users/me/phone.py", line 33, in <module>
client.loop.run_until_complete(main())
File "/usr/local/Cellar/python#3.9/3.9.1_7/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete
return future.result()
File "/Users/me/phone.py", line 17, in main
result = await client(functions.contacts.ImportContactsRequest(
File "/usr/local/lib/python3.9/site-packages/telethon/client/users.py", line 30, in __call__
return await self._call(self._sender, request, ordered=ordered)
File "/usr/local/lib/python3.9/site-packages/telethon/client/users.py", line 58, in _call
future = sender.send(request, ordered=ordered)
File "/usr/local/lib/python3.9/site-packages/telethon/network/mtprotosender.py", line 174, in send
state = RequestState(request)
File "/usr/local/lib/python3.9/site-packages/telethon/network/requeststate.py", line 17, in __init__
self.data = bytes(request)
File "/usr/local/lib/python3.9/site-packages/telethon/tl/tlobject.py", line 194, in __bytes__
return self._bytes()
File "/usr/local/lib/python3.9/site-packages/telethon/tl/functions/contacts.py", line 498, in _bytes
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.contacts)),b''.join(x._bytes() for x in self.contacts),
File "/usr/local/lib/python3.9/site-packages/telethon/tl/functions/contacts.py", line 498, in <genexpr>
b'\x15\xc4\xb5\x1c',struct.pack('<i', len(self.contacts)),b''.join(x._bytes() for x in self.contacts),
File "/usr/local/lib/python3.9/site-packages/telethon/tl/types/__init__.py", line 9789, in _bytes
self.serialize_bytes(self.phone),
File "/usr/local/lib/python3.9/site-packages/telethon/tl/tlobject.py", line 112, in serialize_bytes
raise TypeError(
TypeError: bytes or str expected, not <class 'list'>
Here is the same code but the phone number to check is "hardcoded"
import random
from telethon import TelegramClient
from telethon import functions, types
api_id = XXXXXXX
api_hash = 'XXXXXXXXXXXXXXXXX'
client = TelegramClient('session', api_id, api_hash)
async def main():
phone_number = '+XXXXXXXXX'
result = await client(functions.contacts.ImportContactsRequest(
contacts=[types.InputPhoneContact(
client_id=random.randrange(-2**63, 2**63),
phone=phone_number,
first_name='Some Name',
last_name=''
)]
))
if len(result.users):
print(f"{phone_number} has a telegram account")
await client(functions.contacts.DeleteContactsRequest(result.users))
else:
print(f"couldn't find an account for {phone_number}")
client.start()
client.loop.run_until_complete(main())
Does anyone know how I can assign the file.txt to the phone_in variable?
If ImportContactsRequests expects one phone number at a time, then you have to call it for each phone number. That will create multiple records for a single name, but if the API doesn't allow multiple phone numbers per person, you'll have to decide how to handle it.
with open('file.txt', 'r') as f:
phone_str = f.readline()
result = await client(functions.contacts.ImportContactsRequest(
contacts=[types.InputPhoneContact(
client_id=random.randrange(-2**63, 2**63),
phone=phone_str,
first_name='Some Name',
last_name=''
)]
))
if len(result.users):
print(f"{phone_number} has a telegram account")
await client(functions.contacts.DeleteContactsRequest(result.users))
else:
print(f"couldn't find an account for {phone_number}")
According to the doc of InputPhoneContact, the phone argument takes string type not list. So you could read all phones in the file.txt first, then loop through the list.
async def main():
phone_in = []
with open('file.txt', 'r') as f:
phone_str = f.readline()
phone_in.append(ast.literal_eval(phone_str))
for phone in phone_in:
result = await client(functions.contacts.ImportContactsRequest(
contacts=[types.InputPhoneContact(
client_id=random.randrange(-2**63, 2**63),
phone=phone,
first_name='Some Name',
last_name=''
)]
))
if len(result.users):
print(f"{phone} has a telegram account")
await client(functions.contacts.DeleteContactsRequest(result.users))
else:
print(f"couldn't find an account for {phone}")
python does allow for creation of heterogeneous lists, so not sure why this is throwing an error. Depending on the version in use, maybe there is a constraint on the type homogeneity in the list.I'm not sure though...but curious to know if the following works?
Can you try with a small version of the file in which the numbers are of the same 'type'?
Alternately, can try with a x.strip("[/{(") before appending it to phone_in.
When I have to deal with that kind of link : https://t.me/channelName
I usually get message from channel like this :
async def main():
channel = await client.get_entity('channelName')
messages = await client.get_messages(channel, limit = N )
#...Code etc..
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
How do you get message if you link is like this ?
https://t.me/joinchat/DDDDDxxxxAAAA
I know that 'DDDDDxxxxAAAA' is the channel_hash, so I joined the channel by telegram client and I tried get channel id and message object :
channel_hash = "DDDDDxxxxAAAA"
channel = await client(functions.messages.CheckChatInviteRequest(hash=channel_hash))
Now , channel object containes channel ID and many others fields.
example : (chat=Channel(id=123456789,...etcc
So , I tried like this:
messages = await client.get_messages(channel, limit = N )
but it returns :
Traceback (most recent call last):
File "C:\Users\****\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\telethon\sessions\memory.py", line 192, in get_input_entity
return utils.get_input_peer(key)
File "C:\Users\****\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\telethon\utils.py", line 235, in get_input_peer
_raise_cast_fail(entity, 'InputPeer')
File "C:\Users\****\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\telethon\utils.py", line 138, in _raise_cast_fail
raise TypeError('Cannot cast {} to any kind of {}.'.format(
TypeError: Cannot cast ChatInviteAlready to any kind of InputPeer.
TypeError: Cannot cast ChatInviteAlready to any kind of InputPeer.
How to get messages if you only know channel hash ?
Thanks for help
Two paho.mqtt clients (client1 and client2) are created in Python, which connects to mosquitto brokers. Two clients subscribe to different topics. client1 runs loop_forever(), and client2 runs loop_start(). client1's on_message() callback stores the message in MySQL database. client2's on_message() callback runs a simple test.
The test contains a test method which uses mock object paho.mqtt.client.MQTTMessage. For client2, I am publishing the message from mosquitto_pub in a command line. when I receive the message to run the test, the test runs successfully. But after that I get this below error message. when I comment the test method which uses this mock object paho.mqtt.client.MQTTMessage for test, I don't get this error message.
Is this error coming from Python or paho.mqtt? or is it from client1.loop_forever() method?
File "/usr/local/lib/python3.6/site-packages/paho_mqtt-1.3.1-py3.6.egg/paho/mqtt/client.py", line 1481, in loop_forever
rc = self.loop(timeout, max_packets)
File "/usr/local/lib/python3.6/site-packages/paho_mqtt-1.3.1-py3.6.egg/paho/mqtt/client.py", line 1003, in loop
rc = self.loop_read(max_packets)
File "/usr/local/lib/python3.6/site-packages/paho_mqtt-1.3.1-py3.6.egg/paho/mqtt/client.py", line 1284, in loop_read
rc = self._packet_read()
File "/usr/local/lib/python3.6/site-packages/paho_mqtt-1.3.1-py3.6.egg/paho/mqtt/client.py", line 1849, in _packet_read
rc = self._packet_handle()
File "/usr/local/lib/python3.6/site-packages/paho_mqtt-1.3.1-py3.6.egg/paho/mqtt/client.py", line 2305, in _packet_handle
return self._handle_publish()
File "/usr/local/lib/python3.6/site-packages/paho_mqtt-1.3.1-py3.6.egg/paho/mqtt/client.py", line 2500, in _handle_publish
self._handle_on_message(message)
File "/usr/local/lib/python3.6/site-packages/paho_mqtt-1.3.1-py3.6.egg/paho/mqtt/client.py", line 2640, in _handle_on_message
for callback in self._on_message_filtered.iter_match(message.topic):
File "/usr/local/lib/python3.6/site-packages/paho_mqtt-1.3.1-py3.6.egg/paho/mqtt/matcher.py", line 60, in iter_match
lst = topic.split('/')
TypeError: a bytes-like object is required, not 'str'
As mentioned in the paho documentation, your topic must be of type bytes:
class MQTTMessage(object):
""" This is a class that describes an incoming or outgoing message. It is
passed to the on_message callback as the message parameter.
Members:
topic : String/bytes. topic that the message was published on.
payload : String/bytes the message payload.
qos : Integer. The message Quality of Service 0, 1 or 2.
retain : Boolean. If true, the message is a retained message and not fresh.
mid : Integer. The message id.
On Python 3, topic must be bytes.
"""
__slots__ = 'timestamp', 'state', 'dup', 'mid', '_topic', 'payload', 'qos', 'retain', 'info'
def __init__(self, mid=0, topic=b""):
self.timestamp = 0
self.state = mqtt_ms_invalid
self.dup = False
self.mid = mid
self._topic = topic
self.payload = b""
self.qos = 0
self.retain = False
self.info = MQTTMessageInfo(mid)
def __eq__(self, other):
"""Override the default Equals behavior"""
if isinstance(other, self.__class__):
return self.mid == other.mid
return False
def __ne__(self, other):
"""Define a non-equality test"""
return not self.__eq__(other)
#property
def topic(self):
if sys.version_info[0] >= 3:
return self._topic.decode('utf-8')
else:
return self._topic
#topic.setter
def topic(self, value):
self._topic = value
-> On Python 3, topic must be bytes.
So ensure that your topic is a bytes object, then it should work
BTW, here a short example for string and byte converting:
mystring = 'hello_string'
b1 = bytes(mystring, 'utf-8')
b2 = str(b1, 'utf-8')
print(b1)
print(b2)
output is:
b'hello_string'
hello_string
I am developing an application on App Engine and Python. This app is meant to create routes to several points in town. To create this routes, I invoke a request to an Arcgis service. Once that is done, I need to check the status of the request and get a JSON with the results. I check these results with the following method:
def store_route(job_id, token):
import requests, json
#Process stops result and store it as json in stops_response
stops_url = "https://logistics.arcgis.com/arcgis/rest/services/World/VehicleRoutingProblem/GPServer/SolveVehicleRoutingProblem/jobs/"
stops_url = stops_url+str(job_id)+"/results/out_stops?token="+str(token)+"&f=json"
stops_r = requests.get(stops_url)
stops_response = json.loads(stops_r.text)
#Process routes result and store it as json in routes_response
routes_url = "https://logistics.arcgis.com/arcgis/rest/services/World/VehicleRoutingProblem/GPServer/SolveVehicleRoutingProblem/jobs/"
routes_url = routes_url+str(job_id)+"/results/out_routes?token="+str(token)+"&f=json"
routes_r = requests.get(routes_url)
routes_response = json.loads(routes_r.text)
from routing.models import ArcGisJob, DeliveryRoute
#Process each route from response
processed_routes = []
for route_info in routes_response['value']['features']:
print route_info
route_name = route_info['attributes']['Name']
coordinates = route_info['geometry']['paths']
coordinates_json = {"coordinates": coordinates}
#Process stops from each route
stops = []
for route_stops in stops_response['value']['features']:
if route_name == route_stops['attributes']['RouteName']:
stops.append({"Name": route_stops['attributes']['Name'],
"Sequence": route_stops['attributes']['Sequence']})
stops_json = {"content": stops}
#Create new Delivery Route object
processed_routes.append(DeliveryRoute(name=route_name,route_coordinates=coordinates_json, stops=stops_json))
#insert a new Job table entry with all processed routes
new_job = ArcGisJob(job_id=str(job_id), routes=processed_routes)
new_job.put()
As you can see, what my code does is practically visit the JSON returned by the service and parse it for the content that interest me. The problem is I get the following output:
{u'attributes': {
u'Name': u'ruta_4855443348258816',
...
u'StartTime': 1427356800000},
u'geometry': {u'paths': [[[-100.37766063699996, 25.67669987000005],
...
[-100.37716999999998, 25.67715000000004],
[-100.37766063699996, 25.67669987000005]]]}}
ERROR 2015-03-26 19:02:58,405 handlers.py:73] 'geometry'
Traceback (most recent call last):
File "/Users/Vercetti/Dropbox/Logyt/Quaker Routing/logytrouting/routing/handlers.py", line 68, in get
arc_gis.store_route(job_id, token)
File "/Users/Vercetti/Dropbox/Logyt/Quaker Routing/logytrouting/libs/arc_gis.py", line 150, in store_route
coordinates = route_info['geometry']['paths']
KeyError: 'geometry'
ERROR 2015-03-26 19:02:58,412 BaseRequestHandler.py:51] Traceback (most recent call last):
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 570, in dispatch
return method(*args, **kwargs)
File "/Users/Vercetti/Dropbox/Logyt/Quaker Routing/logytrouting/routing/handlers.py", line 68, in get
arc_gis.store_route(job_id, token)
File "/Users/Vercetti/Dropbox/Logyt/Quaker Routing/logytrouting/libs/arc_gis.py", line 150, in store_route
coordinates = route_info['geometry']['paths']
KeyError: 'geometry'
The actual JSON returned has a lot more of info, but i just wrote a little portion of it so you can see that there IS a 'geometry' key. Any idea why I get this error??