FlaskInjector : Working outside of request context - python-3.x

I am building a flask webapp that communicates with another application through http requests. So I am trying to using dependency injection for the httpClient object.
Here is the code
class HttpClient(object):
def __init__(self, host):
self.host = host
self.httpclient = 3partyModule.connect(url=host,
verbose=False,
max_greenlets=1)
def configure(binder):
binder.bind(HttpClient, to=HttpClient, scope=singleton)
if __name__ == '__main__':
app = Flask(__name__)
FlaskInjector(app=app, modules=[configure])
app.run()
When I run the application, I get the following error -
Exception has occurred: RuntimeError
Working outside of request context.
This typically means that you attempted to use functionality that needed
an active HTTP request. Consult the documentation on testing for
information about how to avoid this problem.
I have tried to lookup on this, but could not find any helpful lead.
Appreciate if anyone can shed some light on the issue here.
Thank you in advance.
Package Versions:
Flask==2.0.1
Flask-Injector==0.12.3
Python==3.8

Check your Werkzeug version. Noticed this issue with Werkzeug==2.0.1. Had to rollback to Werkzeug==0.15.2.
pip install --upgrade Werkzeug==0.15.2

I had this issue with Flask-Injector==0.12.3 and managed to resolve it by upgrading to Flask-Injector==0.13.0

Related

AZURE FUNCTIONS: PDFInfoNotInstalledError: Unable to get page count. Is poppler installed and in PATH? for pdf2image

I am getting this error "Result: Failure Exception: PDFInfoNotInstalledError: Unable to get page count. Is poppler installed and in PATH? for azure functions."
I am using pdf2image library's convert_from_path() to process my pdf to image. This works fine while I test from local. While publishing the function to azure, poppler-utils package also gets installed there but still the error comes. I saw a lot of threads related to this error and tried it but wanted to know , if anyone experienced this specifically for azure functions.
Suggestion for this issue has been provided in the thread
"you should try to troubleshoot it by simply having a function that opens a process and prints the help of pdftoppm (poppler). You will be able to get a different message that might be more relevant.
Something like this:
import subprocess
def main():
p = subprocess.Popen(["pdftoppm", "-h"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
print(out, err)
As a general recommendation, I would bundle the poppler utilities with your package to avoid installing it in the function environment. You can call the function with poppler_path."

boto3 refers FEATURE_OCSP_MODE when setting IP address, but cannot find document about it

I got the following error message:
An HTTP Client raised and unhandled exception: name 'FEATURE_OCSP_MODE' is not defined.
However, I cannot find any reference on the internet about this FEATURE_OCSP_MODE. I was calling describe_addresses() of boto3 using Pythan 3.8. The code was working until yesterday (8/24/2020).
I have just faced the same problem and the root cause was the snowflake-connector-python version as mentioned by Ben Campbell. In version v2.3.0 they accidentally removed the 'FEATURE_OCSP_MODE' constant but in version v2.3.1 they added it back.
The solution is to use snowflake-connector-python==2.3.1 or a newer one.
I rolled back to boto3==1.14.46 and snowflake-connector-python==2.2.10 as I was getting errors in both within Airflow 1.10.10 on Python 3.6.
This did the trick.

Not able to connect with slack_rtm

I'm trying to build a slack bot with this turorial i managed with all the modules except the slack
when I am trying to connect the slack_rtm having error like this. I'm using python 3.7.5, slackclient==1.3.1 and also using proper app token. Im stuck here for long time please help!
Failed RTM connect
Traceback (most recent call last):
File "E:\Geeksters-Slack-Chatbot-master\venv\lib\site-packages\slackclient\client.py", line 140, in rtm_connect
self.server.rtm_connect(use_rtm_start=with_team_state, **kwargs)
File "E:\Geeksters-Slack-Chatbot-master\venv\lib\site-packages\slackclient\server.py", line 163, in rtm_connect
raise SlackLoginError(reply=reply)
slackclient.server.SlackLoginError
Connection Failed
check my code
from slackclient import SlackClient
SLACK_API_TOKEN = "Unsing_proper_token_here"
client = SlackClient(SLACK_API_TOKEN)
def say_hello(data):
if 'Hello' in data['text']:
channel_id = data['channel']
thread_ts = data['ts']
user = data['user']
client.api_call('chat.postMessage',
channel=channel_id,
text="Hi <#{}>!".format(user),
thread_ts=thread_ts
)
if client.rtm_connect():
while client.server.connected is True:
for data in client.rtm_read():
if "type" in data and data["type"] == "message":
say_hello(data)
else:
print("Connection Failed")
There is an issue with RTM when using the OAUTH tokens with the version of slackclient you are using. I suggest trying to revert back to the legacy token that can be found here. For more on this issue i suggest you look at the github issue
It might be related to the Slack App. RTM isn't supported for the new Slack App granular scopes (see python client issue #584 and node client issue #921). If you want to use RTM, you can create a classic slack app with the OAuth Scope bot. Note that a similar question has been asked before.

How to get messages from googles Pub/Sub sytsem by using the current pubsub subsciber

I need to receive published messages from googles Pub/Sub system by using a python based subscriber.
For this I did the following steps:
On the web console I created a project, a registry, a telemetry topic, a device and attached a subscription topic to the telemtry topic
A the Moment my code can publish messages over the mqtt bridge and also the publish functionality of the pubsub library
I can pull this messages over the terminal by using the following cmd:
gcloud pubsub subscriptions pull --auto-ack projects/{project_id}/subscriptions/{subscription_topic}
In the following you see the important snippet of my code. It is based on the git-examples but some functions do not seem to exist anymore in version 0.39.1 of the google-cloud-pubsub package. One example is the subscriber.subscription_path() method.
def receive_messages(subscription_path, service_account_json):
import time
from google.cloud import pubsub_v1
subscriber = pubsub_v1.SubscriberClient(credentials=service_account_json)
#subscription_path = subscriber.subscription_path(
# project_id, subscription_name)
def callback(message):
print('Received message: {}'.format(message))
message.ack()
subscriber.subscribe(subscription_path, callback=callback)
print('Listening for messages on {}'.format(subscription_path))
while True:
time.sleep(60)
When I run this function, countless threads are started in the background bit by bit, but none of them seem to ever quit or start the callback function.
I hopefully installed all requirements:
pip3 freeze
asn1crypto==0.24.0
cachetools==3.0.0
certifi==2018.11.29
cffi==1.11.5
chardet==3.0.4
cryptography==2.4.2
google-api-core==1.7.0
google-api-python-client==1.7.5
google-auth==1.6.2
google-auth-httplib2==0.0.3
google-auth-oauthlib==0.2.0
google-cloud-bigquery==1.8.1
google-cloud-core==0.29.1
google-cloud-datastore==1.7.3
google-cloud-monitoring==0.31.1
google-cloud-pubsub==0.39.1
google-resumable-media==0.3.2
googleapis-common-protos==1.5.6
grpc-google-iam-v1==0.11.4
grpcio==1.17.1
httplib2==0.12.0
idna==2.8
keyring==10.1
keyrings.alt==1.3
oauthlib==3.0.0
paho-mqtt==1.4.0
protobuf==3.6.1
pyasn1==0.4.5
pyasn1-modules==0.2.3
pycparser==2.19
pycrypto==2.6.1
pycurl==7.43.0
pygobject==3.22.0
PyJWT==1.6.4
python-apt==1.4.0b3
pytz==2018.9
pyxdg==0.25
redis==3.0.1
requests==2.21.0
requests-oauthlib==1.2.0
RPi.GPIO==0.6.5
rsa==4.0
SecretStorage==2.3.1
six==1.12.0
unattended-upgrades==0.1
uritemplate==3.0.0
urllib3==1.24.1
virtualenv==16.2.0
I run that code on debian aswell on windows 10 and updated the gcloud:
gcloud components update
For the past week, I've been trying different solutions out of the way or starting the seemingly obsolete google examples. Also, the documentation, which seems even older than the code examples did not help with. So I hope someone here can help me to finally receive python-based client messages via the Pub/Sub-Sytsem.
I hope I could provide the most important information and thank you in advance for your effort to help me.
The examples maintained on the python documentation site here should be up to date. Make sure that you've followed all the steps in the "In order to use this library, you first need to go through the following steps" section before running any code. In particular, you may not have properly set up authentication, I don't believe you should be passing the credentials path manually.
def callback(message: pubsub_v1.subscriber.message.Message) -> None:
print(f"Received {message}.")
message.ack()
streaming_pull_future = subscriber.subscribe(subscription_path,
callback=callback)
print(f"Listening for messages on {subscription_path}..\n")
try:
streaming_pull_future.result(timeout=timeout)
except TimeoutError:
streaming_pull_future.cancel() # Trigger the shutdown.
streaming_pull_future.result() # Block until the shutdown is

bottle.py WSGI server stops responding

I'm trying to build a simple API with the bottle.py (Bottle v0.11.4) web framework. To 'daemonize' the app on my server (Ubuntu 10.04.4), I'm running the shell
nohup python test.py &
, where test.py is the following python script:
import sys
import bottle
from bottle import route, run, request, response, abort, hook
#hook('after_request')
def enable_cors():
response.headers['Access-Control-Allow-Origin'] = '*'
#route('/')
def ping():
return 'Up and running!'
if __name__ == '__main__':
run(host=<my_ip>, port=3000)
I'm running into the following issue:
This works initially but the server stops responding after some time (~24hours). Unfortunately, the logs don't contain any revealing error messages.
The only way I have been able to reproduce the issue is when I try to run a second script on my Ubuntu server that creates another server listening to a different port (ie.: exactly the same script as above but port=3001). If I send a request to the newly created server, I also do not get a response and the connection eventually times out.
Any suggestions are greatly appreciated. I'm new to this, so if there's something fundamentally wrong with this approach, any links to reference guides would also be appreciated. Thank you!
Can you make sure the server isn't sleeping.
If it is, try enabling Wake On LAN http://ubuntuforums.org/showthread.php?t=234588

Resources