Expected bytes, HTTPResponse found - python

I want to use linebot to make an object detection application, and when I retrieve the url which is a http type, the system called an error.
[2022-11-23 19:13:12,335] ERROR in app: Exception on /callback [POST]
Traceback (most recent call last):
File "C:\officiallandprice\myproject\myenv\lib\site-packages\flask\app.py", line 2525, in wsgi_app
response = self.full_dispatch_request()
File "C:\officiallandprice\myproject\myenv\lib\site-packages\flask\app.py", line 1822, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\officiallandprice\myproject\myenv\lib\site-packages\flask\app.py", line 1820, in full_dispatch_request
rv = self.dispatch_request()
File "C:\officiallandprice\myproject\myenv\lib\site-packages\flask\app.py", line 1796, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
File "part1deploy_3.py", line 55, in callback
handler.handle(body, signature)
File "C:\officiallandprice\myproject\myenv\lib\site-packages\linebot\webhook.py", line 259, in handle
self.__invoke_func(func, event, payload)
File "C:\officiallandprice\myproject\myenv\lib\site-packages\linebot\webhook.py", line 271, in __invoke_func
func(event)
File "part1deploy_3.py", line 201, in handle_content_message
text_detected1=text_detected(user.user_id)
File "part1deploy_3.py", line 81, in text_detected
image = vision.Image(content=input_file)
File "C:\officiallandprice\myproject\myenv\lib\site-packages\proto\message.py", line 604, in __init__
super().__setattr__("_pb", self._meta.pb(**params))
TypeError: expected bytes, HTTPResponse found
127.0.0.1 - - [23/Nov/2022 19:13:12] "POST /callback HTTP/1.1" 500 -
I do not have ideas which part of the code below requires a byte type file to make a detection(the PIL module?).
Is it necessary to change to the byte type, when it comes to an object detection?
def text_detected(user_id):
input_file=urllib.request.urlopen (
'https://storage.googleapis.com/
img_platecapture/{}.jpg'.format(user_id))
image = vision.Image(content=input_file)
response = vision_client.text_detection(image=image)
if response.error.message:
raise Exception(
'{}\nFor more info on error messages, check: '
'https://cloud.google.com/apis/design/errors'.format(
response.error.message))
img = Image.open(input_file)
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("simsun.ttc", 18)
for text in response.text_annotations[1::]:
ocr = text.description
draw.text((bound.vertices[0].x-25, bound.vertices[0].y-25),ocr,fill=(255,0,0),font=font)
draw.polygon(
[
bound.vertices[0].x,
bound.vertices[0].y,
bound.vertices[1].x,
bound.vertices[1].y,
bound.vertices[2].x,
bound.vertices[2].y,
bound.vertices[3].x,
bound.vertices[3].y,
],
None,
'yellow',
)
texts=response.text_annotations
a=str(texts[0].description.split())
b=re.sub(u"([^\u4e00-\u9fa5\u0030-u0039])","",a)
b1="".join(b)
print("偵測到的地址為:",b1)
return b1
#handler.add(MessageEvent, message=ImageMessage)
def handle_content_message(event):
message_content = line_bot_api.get_message_content(event.message.id)
user = line_bot_api.get_profile(event.source.user_id)
data=b''
for chunk in message_content.iter_content():
data+= chunk
global bucket_name
bucket_name = 'img_platecapture'
bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(f'{user.user_id}.jpg')
blob.upload_from_string(data)
text_detected1=text_detected(user.user_id) ####Here's the problem
line_bot_api.reply_message(
event.reply_token,
messages=TextSendMessage(
text=text_detected1
))

Related

Python Flask TypeError: Object of type NoSectionError is not JSON serializable

I'm developing an application with python and Flask to automate sending emails.
When I run this application locally, there is no problem, but after deploying the application in Azure, this error appears
TypeError: Object of type NoSectionError is not JSON serializable
The function that is bursting the error is this, when I try to return the dictionary variable
#app.route('/send_email', methods=['POST'])
def get_parameters():
"""
It receives a JSON object, prints it, and then calls another function that sends an email
:return: The result of the function send_email_to_customer
"""
user_input = request.json
print("Conteudo ", user_input)
try:
user = get_config_data(iten_title='EMAIL_LOGIN', iten='email')
psw = get_config_data(iten_title='EMAIL_LOGIN', iten='password')
id_meeting = user_input['id']
list_of_recipients = user_input['recipients']
creator_name = user_input['creator_name']
date_list = user_input['meeting_day']
subject = f'Melhor data para a reuniao {id_meeting}'
url = "https://easy-meeting.azurewebsites.net/external_url?meeting_day="+",".join(date_list)
email_server = create_email_server(user, psw)
for recipients_dict in list_of_recipients:
email_msg = create_email_body(user, recipients_dict, creator_name, subject, url)
run(email_server, email_msg)
dictionary = {"Status":"Sucesso ao enviar o email"}
except Exception as email_error:
dictionary = {"Status":"Erro ao enviar o email", "Error Message": email_error}
print(email_error)
dictionary = jsonify(dictionary)
return dictionary
full error code
2022-11-26T02:26:55.182403211Z [2022-11-26 02:26:55,162] ERROR in app: Exception on /send_email [POST]
2022-11-26T02:26:55.182438711Z Traceback (most recent call last):
2022-11-26T02:26:55.182445810Z File "/tmp/8dacf551bd5f657/antenv/lib/python3.10/site-packages/flask/app.py", line 2525, in wsgi_app
2022-11-26T02:26:55.182480710Z response = self.full_dispatch_request()
2022-11-26T02:26:55.182501610Z File "/tmp/8dacf551bd5f657/antenv/lib/python3.10/site-packages/flask/app.py", line 1822, in full_dispatch_request
2022-11-26T02:26:55.182505610Z rv = self.handle_user_exception(e)
2022-11-26T02:26:55.182509810Z File "/tmp/8dacf551bd5f657/antenv/lib/python3.10/site-packages/flask/app.py", line 1820, in full_dispatch_request
2022-11-26T02:26:55.182513410Z rv = self.dispatch_request()
2022-11-26T02:26:55.182516910Z File "/tmp/8dacf551bd5f657/antenv/lib/python3.10/site-packages/flask/app.py", line 1796, in dispatch_request
2022-11-26T02:26:55.182520410Z return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
2022-11-26T02:26:55.182524010Z File "/tmp/8dacf551bd5f657/api_run.py", line 55, in get_parameters
2022-11-26T02:26:55.182527510Z dictionary = jsonify(dictionary)
2022-11-26T02:26:55.182531010Z File "/tmp/8dacf551bd5f657/antenv/lib/python3.10/site-packages/flask/json/__init__.py", line 342, in jsonify
2022-11-26T02:26:55.182534510Z return current_app.json.response(*args, **kwargs)
2022-11-26T02:26:55.182538010Z File "/tmp/8dacf551bd5f657/antenv/lib/python3.10/site-packages/flask/json/provider.py", line 309, in response
2022-11-26T02:26:55.182541510Z f"{self.dumps(obj, **dump_args)}\n", mimetype=mimetype
2022-11-26T02:26:55.182545110Z File "/tmp/8dacf551bd5f657/antenv/lib/python3.10/site-packages/flask/json/provider.py", line 230, in dumps
2022-11-26T02:26:55.182548610Z return json.dumps(obj, **kwargs)
2022-11-26T02:26:55.182551910Z File "/opt/python/3.10.4/lib/python3.10/json/__init__.py", line 238, in dumps
2022-11-26T02:26:55.182555410Z **kw).encode(obj)
2022-11-26T02:26:55.182558710Z File "/opt/python/3.10.4/lib/python3.10/json/encoder.py", line 199, in encode
2022-11-26T02:26:55.182562210Z chunks = self.iterencode(o, _one_shot=True)
2022-11-26T02:26:55.182565610Z File "/opt/python/3.10.4/lib/python3.10/json/encoder.py", line 257, in iterencode
2022-11-26T02:26:55.182569210Z return _iterencode(o, 0)
2022-11-26T02:26:55.182572510Z File "/tmp/8dacf551bd5f657/antenv/lib/python3.10/site-packages/flask/json/provider.py", line 122, in _default
2022-11-26T02:26:55.182576010Z raise TypeError(f"Object of type {type(o).__name__} is not JSON serializable")
2022-11-26T02:26:55.182579609Z TypeEr
I already tried to add the jsonify flask function, but it didn't work
The goal is to make the dictionary variable just like local
enter image description here

How can i fix the gas price issue in Thirdweb Python SDK Goerli TestNet

Im working with the Thirdweb Python SDK API. The code below sometimes work and sometimes throws a gasprice issue. I think it could be a network issue, because it works sometimes and generates the NFT but not always.
And when i got an error it is about gasprice. But in the Thirdweb API doesnt appear a gasprice argument or someting like this.
Any ideas?
Code:
sqlcol="SELECT ID,(SELECT contrato FROM colecciones WHERE ID=idcolec) AS contratonft FROM solicitudcert WHERE ID='" + idsolicitud + "' LIMIT 0, 1"
mycursor.execute(sqlcol)
misolicitud = mycursor.fetchone()
if(misolicitud):
contratonft_aux=str(misolicitud[1])
contratonft=contratonft_aux.replace('"','')
sdk = ThirdwebSDK.from_private_key(PRIVATE_KEY, NETWORK)
NFT_COLLECTION_ADDRESS = contratonft
nft_collection = sdk.get_nft_collection(NFT_COLLECTION_ADDRESS)
urlarchivoarr=imagencert.split("/")
urlarchivostr=str(urlarchivoarr[1]);
urlarchivoimg="https://files.avfenixrecords.com/" + urlarchivostr
# You can pass in any address here to mint the NFT to
tx = nft_collection.mint(NFTMetadataInput.from_json({
"name": nombrecert,
"description": descripcert,
"image": urlarchivoimg
}))
idnft=tx.id
return jsonify({'status':'OK','IDNFT':idnft})
else:
return jsonify({'status':'ERROR','IDNFT':"NULL"})
Error:
[2022-11-15 19:54:21,628] ERROR in app: Exception on /api/contracts/v1/mintnft [POST]
Traceback (most recent call last):
File "/home/ombhkqgo/virtualenv/contratos/3.8/lib/python3.8/site-packages/flask/app.py", line 2525, in wsgi_app
response = self.full_dispatch_request()
File "/home/ombhkqgo/virtualenv/contratos/3.8/lib/python3.8/site-packages/flask/app.py", line 1822, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/ombhkqgo/virtualenv/contratos/3.8/lib/python3.8/site-packages/flask_cors/extension.py", line 165, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
File "/home/ombhkqgo/virtualenv/contratos/3.8/lib/python3.8/site-packages/flask/app.py", line 1820, in full_dispatch_request
rv = self.dispatch_request()
File "/home/ombhkqgo/virtualenv/contratos/3.8/lib/python3.8/site-packages/flask/app.py", line 1796, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
File "app.py", line 1851, in mintnft
tx = nft_collection.mint(NFTMetadataInput.from_json({
File "/home/ombhkqgo/virtualenv/contratos/3.8/lib/python3.8/site-packages/thirdweb/contracts/nft_collection.py", line 135, in mint
return self.mint_to(self._contract_wrapper.get_signer_address(), metadata)
File "/home/ombhkqgo/virtualenv/contratos/3.8/lib/python3.8/site-packages/thirdweb/contracts/nft_collection.py", line 166, in mint_to
receipt = self._contract_wrapper.send_transaction("mint_to", [to, uri])
File "/home/ombhkqgo/virtualenv/contratos/3.8/lib/python3.8/site-packages/thirdweb/core/classes/contract_wrapper.py", line 113, in send_transaction
tx = getattr(self._contract_abi, fn).build_transaction(
File "/home/ombhkqgo/virtualenv/contratos/3.8/lib/python3.8/site-packages/thirdweb/abi/token_erc721.py", line 1638, in build_transaction
return self._underlying_method(to, uri).buildTransaction(
File "/home/ombhkqgo/virtualenv/contratos/3.8/lib/python3.8/site-packages/web3/contract.py", line 1079, in buildTransaction
return build_transaction_for_function(
File "/home/ombhkqgo/virtualenv/contratos/3.8/lib/python3.8/site-packages/web3/contract.py", line 1648, in build_transaction_for_function
prepared_transaction = fill_transaction_defaults(web3, prepared_transaction)
File "cytoolz/functoolz.pyx", line 249, in cytoolz.functoolz.curry.__call__
File "/home/ombhkqgo/virtualenv/contratos/3.8/lib/python3.8/site-packages/web3/_utils/transactions.py", line 114, in fill_transaction_defaults
default_val = default_getter(web3, transaction)
File "/home/ombhkqgo/virtualenv/contratos/3.8/lib/python3.8/site-packages/web3/_utils/transactions.py", line 60, in <lambda>
'gas': lambda web3, tx: web3.eth.estimate_gas(tx),
File "/home/ombhkqgo/virtualenv/contratos/3.8/lib/python3.8/site-packages/web3/eth.py", line 825, in estimate_gas
return self._estimate_gas(transaction, block_identifier)
File "/home/ombhkqgo/virtualenv/contratos/3.8/lib/python3.8/site-packages/web3/module.py", line 57, in caller
result = w3.manager.request_blocking(method_str,
File "/home/ombhkqgo/virtualenv/contratos/3.8/lib/python3.8/site-packages/web3/manager.py", line 198, in request_blocking
return self.formatted_response(response,
File "/home/ombhkqgo/virtualenv/contratos/3.8/lib/python3.8/site-packages/web3/manager.py", line 171, in formatted_response
raise ValueError(response["error"])
ValueError: {'code': -32000, 'message': 'err: max fee per gas less than block base fee: address 0x98E0463643b28E24223d2B5EF19E78A9AF031505, maxFeePerGas: 70565183066 baseFee: 77047968359 (supplied gas 22141296)'}
I tried to modify the contracts config into the thirdweb dashboard without success.
What network are you seeing this issue on? We can add in a method to manually overwrite gas limits in the SDK.

TypeError: Cannot convert input[[['2017-01-01', None, None]]] of type <class 'list'> to Timestamp

I am trying to create a web API for Swagger UI. It is a time series data modelled using ARIMA. The data frame contains four columns: year (timestamp), male_hourly_wage (float), female_hourly_wage (float), and wage gap (float) which is the target variable. The error appears when I click execute. Any help is appreciated; here's my code:
import pickle
from flask import Flask, request
import pandas as pd
import flasgger
from flasgger import Swagger
app = Flask(__name__)
Swagger(app)
pickle_in = open('model.pkl', 'rb')
model = pickle.load(pickle_in)
#app.route('/')
def welcome():
return 'Welcome All'
#app.route('/predict', methods=['GET'])
def wage_gap_predictor():
"""Let's predict the Wage Gap
This is using docstrings for specifications.
---
parameters:
- name: year
in: query
type: string
format: date
required: false
- name: male_hourly_wages
in: query
type: number
required: true
- name: female_hourly_wages
in: query
type: number
required: true
responses:
200:
description: The output values
"""
#df = pd.read_csv('df_model.csv', parse_dates=True, index_col=0)
year = request.args.get('year')
male_hourly_wage = request.args.get('male_hourly_wage')
female_hourly_wage = request.args.get('female_hourly_wage')
pred = model.predict([[year, male_hourly_wage, female_hourly_wage]])
print(pred)
return 'The predicted wage gap is '+str(pred)
if __name__ == '__main__':
app.run(host='0.0.0.0',port=8000,debug=True)
And I'm getting the following error message:
127.0.0.1 - - [25/Oct/2022 16:12:50] "GET /predict?year=2017-01-01&male_hourly_wages=39.97&female_hourly_wages=32.63 HTTP/1.1" 500 -
Traceback (most recent call last):
File "C:\Users\user\anaconda3\envs\snowflakes\lib\site-packages\flask\app.py", line 2095, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\user\anaconda3\envs\snowflakes\lib\site-packages\flask\app.py", line 2080, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\user\anaconda3\envs\snowflakes\lib\site-packages\flask\app.py", line 2077, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\user\anaconda3\envs\snowflakes\lib\site-packages\flask\app.py", line 1525, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\user\anaconda3\envs\snowflakes\lib\site-packages\flask\app.py", line 1523, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\user\anaconda3\envs\snowflakes\lib\site-packages\flask\app.py", line 1509, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "C:\Users\user\Documents\DataWarehouseTeam\Project_work\Hamoye-Data-Warehouse-ProjectTeam\app2.py", line 51, in wage_gap_predictor
pred = model.predict([[year, male_hourly_wage, female_hourly_wage]], dynamic=True)
File "C:\Users\user\anaconda3\envs\snowflakes\lib\site-packages\statsmodels\base\wrapper.py", line 113, in wrapper
obj = data.wrap_output(func(results, *args, **kwargs), how)
File "C:\Users\user\anaconda3\envs\snowflakes\lib\site-packages\statsmodels\tsa\statespace\mlemodel.py", line 3403, in predict
prediction_results = self.get_prediction(start, end, dynamic, **kwargs)
File "C:\Users\user\anaconda3\envs\snowflakes\lib\site-packages\statsmodels\tsa\statespace\mlemodel.py", line 3287, in get_prediction
self.model._get_prediction_index(start, end, index))
File "C:\Users\user\anaconda3\envs\snowflakes\lib\site-packages\statsmodels\tsa\base\tsa_model.py", line 834, in _get_prediction_index
return get_prediction_index(
File "C:\Users\user\anaconda3\envs\snowflakes\lib\site-packages\statsmodels\tsa\base\tsa_model.py", line 356, in get_prediction_index
start, _, start_oos = get_index_label_loc(
File "C:\Users\user\anaconda3\envs\snowflakes\lib\site-packages\statsmodels\tsa\base\tsa_model.py", line 243, in get_index_label_loc
loc, index, index_was_expanded = get_index_loc(key, index)
File "C:\Users\user\anaconda3\envs\snowflakes\lib\site-packages\statsmodels\tsa\base\tsa_model.py", line 152, in get_index_loc
File "pandas\_libs\tslibs\timestamps.pyx", line 1399, in pandas._libs.tslibs.timestamps.Timestamp.__new__
File "pandas\_libs\tslibs\conversion.pyx", line 446, in pandas._libs.tslibs.conversion.convert_to_tsobject
TypeError: Cannot convert input [[['2017-01-01', None, None]]] of type <class 'list'> to Timestamp

cryptography.fernet.InvalidToken error when retrieving data from SQLalchemy database

Hey I've been trying to encrypt some inputted data into a SQLalchemy database. However I keep receiving this error when trying to retrieve the decyrpted data from the database. Any help would be much appreciated.
key = Fernet.generate_key()
fernet = Fernet(key)
Encryption part:
fnam = str(form.first_name.data.lower())
Cfname = bytes(fnam, 'utf-8')
Efname = str(fernet.encrypt(Cfname))
lnam = str(form.last_name.data.lower())
Clname = bytes(lnam,'utf-8')
Elname = str(fernet.encrypt(Clname))
print(Efname)
print(Elname)
appoint.first_name =Efname
appoint.last_name = Elname
Decryption part:
info = user.query.filter_by(id=user.id).first()
finam = info.first_name
lanam = info.last_name
first = str(fernet.decrypt(bytes(finam,'utf-8')))
last = str(fernet.decrypt(bytes(lanam,'utf-8')))
Error message
Traceback (most recent call last):
File "appsec2\venv\lib\site-packages\flask\app.py", line 2095, in __call__
return self.wsgi_app(environ, start_response)
File "appsec2\venv\lib\site-packages\flask\app.py", line 2080, in wsgi_app
response = self.handle_exception(e)
File "appsec2\venv\lib\site-packages\flask\app.py", line 2077, in wsgi_app
response = self.full_dispatch_request()
File "appsec2\venv\lib\site-packages\flask\app.py", line 1525, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\txzsp\OneDrive\Documents\Poly sch stuff\Y2, S1\appsec2\venv\lib\site-packages\flask\app.py", line 1523, in full_dispatch_request
rv = self.dispatch_request()
File "appsec2\venv\lib\site-packages\flask\app.py", line 1509, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "appsec2\appsec\routes.py", line 908, in retrieveConsultation
first = str(fernet.decrypt(bytes(finam,'utf-8')))
File appsec2\venv\lib\site-packages\cryptography\fernet.py", line 83, in decrypt
timestamp, data = Fernet._get_unverified_token_data(token)
File "appsec2\venv\lib\site-packages\cryptography\fernet.py", line 115, in _get_unverified_token_data
raise InvalidToken
cryptography.fernet.InvalidToken

ValueError: Circular reference detected

I had a code of around 287 lines, when it is executed on command prompt everything works fine, but when it is compiled on localhost with Flask it is showing following error:
ERROR:series-api:Exception on /papis/get-series [GET]
Traceback (most recent call last):
File "C:\Users\mkiak\AppData\Roaming\Python\Python39\site-packages\flask\app.py", line 2070, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\mkiak\AppData\Roaming\Python\Python39\site-packages\flask\app.py", line 1515, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\mkiak\AppData\Roaming\Python\Python39\site-packages\flask\app.py", line 1513, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\mkiak\AppData\Roaming\Python\Python39\site-packages\flask\app.py", line 1499, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "E:\series-api.py", line 275, in getSeries
return jsonify(result)
File "C:\Users\mkiak\AppData\Roaming\Python\Python39\site-packages\flask\json\__init__.py", line 348, in jsonify
f"{dumps(data, indent=indent, separators=separators)}\n",
File "C:\Users\mkiak\AppData\Roaming\Python\Python39\site-packages\flask\json\__init__.py", line 129, in dumps
rv = _json.dumps(obj, **kwargs)
File "C:\Program Files\Python39\lib\json\__init__.py", line 234, in dumps
return cls(
File "C:\Program Files\Python39\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Program Files\Python39\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
ValueError: Circular reference detected
You have a reference to object inside the object itself. Minimal example:
import json
d = {}
d["a"] = d
json.dumps(d) # raises ValueError: Circular reference detected
You can try to create a (deep) copy of the object.
d = {}
d["a"] = d.copy()
json.dumps(d)

Categories

Resources