As the title suggests, I am seeing this error when my flask app tries to run.
I am hosting the application locally using dev_appserver.
The error occurs when I visit the site and it tries to run the app. It appears that GAE is trying and failing to bind a socket for some reason.
I suspect that this may have something to do with OAuth2. Maybe it requires an SSL connection?
I don't even know where to begin solving this as none of the other posts about this are experiencing the same variation of the issue.
Edit: Here's a screenshot of the console confirming that the GAE server launches successfully on a different port; still doesn't resolve it
Traceback (most recent call last):
File "C:\Users\XXX\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\runtime\wsgi.py", line 240, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "C:\Users\XXX\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\runtime\wsgi.py", line 299, in _LoadHandler
handler, path, err = LoadObject(self._handler)
File "C:\Users\XXX\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\runtime\wsgi.py", line 85, in LoadObject
obj = __import__(path[0])
File "C:\Users\XXX\PycharmProjects\ad-assignment\main.py", line 51, in <module>
app.run()
File "C:\Users\XXX\PycharmProjects\ad-assignment\lib\flask\app.py", line 843, in run
run_simple(host, port, self, **options)
File "C:\Users\XXX\PycharmProjects\ad-assignment\lib\werkzeug\serving.py", line 694, in run_simple
inner()
File "C:\Users\XXX\PycharmProjects\ad-assignment\lib\werkzeug\serving.py", line 656, in inner
fd=fd)
File "C:\Users\XXX\PycharmProjects\ad-assignment\lib\werkzeug\serving.py", line 550, in make_server
passthrough_errors, ssl_context, fd=fd)
File "C:\Users\XXX\PycharmProjects\ad-assignment\lib\werkzeug\serving.py", line 464, in __init__
HTTPServer.__init__(self, (host, int(port)), handler)
File "C:\Python27\Lib\SocketServer.py", line 417, in __init__
self.server_bind()
File "C:\Python27\Lib\BaseHTTPServer.py", line 108, in server_bind
SocketServer.TCPServer.server_bind(self)
File "C:\Python27\Lib\SocketServer.py", line 431, in server_bind
self.socket.bind(self.server_address)
File "C:\Users\XXX\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\dist27\socket.py", line 222, in meth
return getattr(self._sock,name)(*args)
File "C:\Users\XXX\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\api\remote_socket\_remote_socket.py", line 676, in bind
raise _SystemExceptionFromAppError(e)
error: [Errno 13] Permission denied
INFO 2016-12-16 21:41:51,631 module.py:788] default: "GET /oauth2callback?code=x/xxxxxxxxxxxxxxxxx HTTP/1.1" 500 -
Code (as seen in Google's OAuth2 usage guide):
import flask
app = flask.Flask(__name__)
#app.route('/')
def index():
...
#app.route('/oauth2callback')
def oauth2callback():
...
if __name__ == 'main':
import uuid
app.secret_key = str(uuid.uuid4())
app.debug = False
app.run()
We have a tutorial that walks you through adding Firebase Authentication to your Python app running with Flask. Firebase Authentication is the preferred identity toolkit now. You can of course still use a pure OAuth2 flow, but Firebase Auth also provides multi-provider authentication if that's something you were considering adding to your app anyways. If you just want to dive into the sample's code its here on GitHub.
If you just want to stick with straight OAuth, you might want to look at your Flask code itself. Getting flask to run is pretty easy on App Engine. My guess is that you're calling some code that you don't need to (flask.run()) or you aren't importing your library properly (see appengine_config.py).
Related
I am stuck in this setup for almost a week now. Hope that someone can guide me through it.
Setup
I have setup an IIS Server running Flask python code. (Using wfastcgi.py )
I have configured the Application Pool Identity to my own account. (Admin Permission)
I have changed all the files permission that are needed for this web deployment to "Everyone" - Full Control(Read,Write,Execute). (I understand the security risks, this is my staging environment.)
Web server is running fine and i have checked using the bottom code to know my python permission is administrator.
def am_i_admin():
try:
is_admin = os.getuid() == 0
except AttributeError:
is_admin = ctypes.windll.shell32.IsUserAnAdmin() != 0
if is_admin == True:
return "ADMIN"
else:
return "USER"
Problem Statement
I am trying to run administrator priv code on my flask IIS server which allow user within the same network to execute; such as
subprocess.run(['ipconfig'], stdout=subprocess.PIPE)
pyautogui.screenshot() #which take a screenshot of the web server and send over to the client.
I ran on my local jupyter notebook, and the above functions worked perfectly well.
But it failed to run on the IIS flask server.
I have also tried to setup pyautogui on flask server (stand alone without IIS), it worked.
What is the issue with the IIS server ?? Or are there more things that i need to configure. Are there security features that I can disable ?
Subprocess error message:
Error occurred while reading WSGI handler:
Traceback (most recent call last):
File "c:\users\aspnet\anaconda3\lib\site-packages\wfastcgi.py", line 791, in main
env, handler = read_wsgi_handler(response.physical_path)
File "c:\users\aspnet\anaconda3\lib\site-packages\wfastcgi.py", line 633, in read_wsgi_handler
handler = get_wsgi_handler(os.getenv("WSGI_HANDLER"))
File "c:\users\aspnet\anaconda3\lib\site-packages\wfastcgi.py", line 600, in get_wsgi_handler
handler = __import__(module_name, fromlist=[name_list[0][0]])
File ".\my_app.py", line 58, in <module>
out = os.popen("ipconfig").read()
File "c:\users\aspnet\anaconda3\lib\os.py", line 990, in popen
bufsize=buffering)
File "c:\users\aspnet\anaconda3\lib\subprocess.py", line 753, in __init__
errread, errwrite) = self._get_handles(stdin, stdout, stderr)
File "c:\users\aspnet\anaconda3\lib\subprocess.py", line 1090, in _get_handles
errwrite = _winapi.GetStdHandle(_winapi.STD_ERROR_HANDLE)
OSError: [WinError 6] The handle is invalid
StdOut:
StdErr:
pyautogui error:
Error occurred while reading WSGI handler:
Traceback (most recent call last):
File "c:\users\aspnet\anaconda3\lib\site-packages\wfastcgi.py", line 791, in main
env, handler = read_wsgi_handler(response.physical_path)
File "c:\users\aspnet\anaconda3\lib\site-packages\wfastcgi.py", line 633, in read_wsgi_handler
handler = get_wsgi_handler(os.getenv("WSGI_HANDLER"))
File "c:\users\aspnet\anaconda3\lib\site-packages\wfastcgi.py", line 600, in get_wsgi_handler
handler = __import__(module_name, fromlist=[name_list[0][0]])
File ".\my_app.py", line 45, in <module>
pyautogui.screenshot()
File "c:\users\aspnet\anaconda3\lib\site-packages\pyscreeze\__init__.py", line 135, in wrapper
return wrappedFunction(*args, **kwargs)
File "c:\users\aspnet\anaconda3\lib\site-packages\pyscreeze\__init__.py", line 427, in _screenshot_win32
im = ImageGrab.grab()
File "c:\users\aspnet\anaconda3\lib\site-packages\PIL\ImageGrab.py", line 44, in grab
include_layered_windows, all_screens
OSError: screen grab failed
StdOut:
StdErr:
File "c:\users\aspnet\anaconda3\lib\site-packages\PIL\ImageGrab.py", line 44, in grab
include_layered_windows, all_screens
OSError: screen grab failed
To resolve the issue set stderr and stdin to subprocess.PIPE:
['where', 'wkhtmltopdf'], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0].strip()
Reference: https://github.com/foliojs/pdfkit/issues/714
File "c:\users\aspnet\anaconda3\lib\site-packages\PIL\ImageGrab.py", line 44, in grab
include_layered_windows, all_screens
OSError: screen grab failed
Use below code:
from PIL import ImageGrab
OR
from PIL import Image
I have developed a flask based app which is running successfully at my local machine / network.
I deployed it to an AWS EC2 instance. Started it like this:
flask run --host <private ip within AWS>
but when I tried to access an implemented API through Postman, I got following error in Postman console:
Error: connect ECONNREFUSED <IPv4 Public IP within AWS>
Noticed that it might be due to the fact that flask app typically runs on port 5000, however the EC2 has inbound rule of type http bound to port 80.
So I changed my flask code to:
if __name__ == "__main__":
app = create_app()
app.run(host='<private ip within AWS>', port=80)
And tried to run it like this in AWS ec2 instance:
python3 apiapp.py
However I got following stack trace while trying to run the app:
Traceback (most recent call last):
File "apiapp.py", line 49, in <module>
app.run(host='<private ip within AWS>', port=80)
File "/home/ec2-user/AwesomeAPIs/venv/lib64/python3.7/site-packages/flask/apiapp.py", line 990, in run
run_simple(host, port, self, **options)
File "/home/ec2-user/AwesomeAPIs/venv/lib64/python3.7/site-packages/werkzeug/serving.py", line 1052, in run_simple
inner()
File "/home/ec2-user/AwesomeAPIs/venv/lib64/python3.7/site-packages/werkzeug/serving.py", line 1005, in inner
fd=fd,
File "/home/ec2-user/AwesomeAPIs/venv/lib64/python3.7/site-packages/werkzeug/serving.py", line 848, in make_server
host, port, app, request_handler, passthrough_errors, ssl_context, fd=fd
File "/home/ec2-user/AwesomeAPIs/venv/lib64/python3.7/site-packages/werkzeug/serving.py", line 740, in __init__
HTTPServer.__init__(self, server_address, handler)
File "/usr/lib64/python3.7/socketserver.py", line 452, in __init__
self.server_bind()
File "/usr/lib64/python3.7/http/server.py", line 137, in server_bind
socketserver.TCPServer.server_bind(self)
File "/usr/lib64/python3.7/socketserver.py", line 466, in server_bind
self.socket.bind(self.server_address)
PermissionError: [Errno 13] Permission denied
Am I missing anything obvious over here?
There is an answer here - File not found on pythonanywhere.com
But it doesn't work in my case.
I have put the file in both the project main directory and the /project/static directory -
My code -
from flask import Flask, render_template, request
from flask_cors import CORS, cross_origin
from diffdiag import DifferentialDiagScript2 as dd
import os
app = Flask(__name__)
app.config['CORS_HEADERS'] = 'Content-Type'
cors = CORS(app, resources={r"/*": {"origins": "*"}})
#app.route('/')
#cross_origin()
def index():
module_dir = os.path.dirname(__file__)
file_path = os.path.join(module_dir, 'literature.csv')
items = list(line.strip() for line in open(file_path))
return render_template('index.html', table = items)
I have also tried -
items = list(line.strip() for line in open(f2))
items = list(line.strip() for line in open('./static/f2'))
items = list(line.strip() for line in open('/home/daddyodevil/add/Automated_DD/f2'))
items = list(line.strip() for line in open('/home/daddyodevil/add/Automated_DD/static/f2'))
Nothing seems to work.
Any help is appreciated.
Edit 1 - Adding complete error
Exception on / [GET]#012Traceback (most recent call last):#012 File "/home/daddyodevil/.local/lib/python3.6/site-packages/flask/app.py", line 2292, in wsgi_app#012 response = self.full_dispatch_request()#012 File "/home/daddyodevil/.local/lib/python3.6/site-packages/flask/app.py", line 1815, in full_dispatch_request#012 rv = self.handle_user_exception(e)#012 File "/home/daddyodevil/.local/lib/python3.6/site-packages/flask_cors/extension.py", line 161, in wrapped_function#012 return cors_after_request(app.make_response(f(*args, **kwargs)))#012 File "/home/daddyodevil/.local/lib/python3.6/site-packages/flask/app.py", line 1718, in handle_user_exception#012 reraise(exc_type, exc_value, tb)#012 File "/home/daddyodevil/.local/lib/python3.6/site-packages/flask/_compat.py", line 35, in reraise#012 raise value#012 File "/home/daddyodevil/.local/lib/python3.6/site-packages/flask/app.py", line 1813, in full_dispatch_request#012 rv = self.dispatch_request()#012 File "/home/daddyodevil/.local/lib/python3.6/site-packages/flask/app.py", line 1799, in dispatch_request#012 return self.view_functions[rule.endpoint](**req.view_args)#012 File "/home/daddyodevil/.local/lib/python3.6/site-packages/flask_cors/decorator.py", line 128, in wrapped_function#012 resp = make_response(f(*args, **kwargs))#012 File "/home/daddyodevil/add/Automated_DD/app.py", line 13, in index#012 items = list(line.strip() for line in open("./static/f2"))#012FileNotFoundError: [Errno 2] No such file or directory: './static/f2'
Edit 2 - Adding error received when trying to run app.py in pythonanywhere
* Serving Flask app "app" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: off
Traceback (most recent call last):
File "/home/daddyodevil/add/Automated_DD/app.py", line 47, in <module>
app.run()
File "/home/daddyodevil/.local/lib/python3.6/site-packages/flask/app.py", line 943, in run
run_simple(host, port, self, **options)
File "/home/daddyodevil/.local/lib/python3.6/site-packages/werkzeug/serving.py", line 814, in run_simple
inner()
File "/home/daddyodevil/.local/lib/python3.6/site-packages/werkzeug/serving.py", line 774, in inner
fd=fd)
File "/home/daddyodevil/.local/lib/python3.6/site-packages/werkzeug/serving.py", line 660, in make_server
passthrough_errors, ssl_context, fd=fd)
File "/home/daddyodevil/.local/lib/python3.6/site-packages/werkzeug/serving.py", line 577, in __init__
self.address_family), handler)
File "/usr/lib/python3.6/socketserver.py", line 453, in __init__
self.server_bind()
File "/usr/lib/python3.6/http/server.py", line 136, in server_bind
socketserver.TCPServer.server_bind(self)
File "/usr/lib/python3.6/socketserver.py", line 467, in server_bind
self.socket.bind(self.server_address)
OSError: [Errno 98] Address already in use
Running app.py in a PythonAnywhere console is unlikely to work -- it will try to bind to a port and listen for connections, and it's entirely possible that someone else is using the port.
The problem you're seeing in your website error log is because you're trying to open the file './static/f2'. This path with be resolved relative to the directory where the application is running, which is not necessarily the same as the directory containing the module, and might not be the main directory either.
If you want to load up the one in the same directory as the module, and you already have code to work out the module directory like this
module_dir = os.path.abspath(os.path.dirname(__file__))
...then you can change your code to use that module_dir by changing the line
items = list(line.strip() for line in open("./static/f2"))
...to be this:
items = list(line.strip() for line in open(os.path.join(module_dir, "./static/f2")))
The linked answer doesn't work for you because you haven't followed it properly. Wrap your module directory inside os.path.abspath() in order to get the absolute path as the linked answer suggests:
module_dir = os.path.abspath(os.path.dirname(__file__))
Edit
Also ensure that this file actually exists relative to your module directory:
'./static/f2'
Because that's where the exception is being thrown (look at the last line of the stack trace):
items = list(line.strip() for line in open("./static/f2"))
#012FileNotFoundError: [Errno 2] No such file or directory: './static/f2'
I am trying to right a Google Cloud Platform app in python with Flask that makes an MQTT connection. I have included the paho python library by doing pip install paho-mqtt -t libs/. However, when I try to run the app, even if I don't try to connect to MQTT. I get a weird error about IP address checking:
RuntimeError: error('illegal IP address string passed to inet_pton',)
It seems something in the remote_socket lib is causing a problem. Is this a security issue? Is there someway to disable it?
Relevant code:
from flask import Flask
import paho.mqtt.client as mqtt
import logging as logger
app = Flask(__name__)
# Note: We don't need to call run() since our application is embedded within
# the App Engine WSGI application server.
#callback to print out connection status
def on_connect(mosq, obj, rc):
logger.info('on_connect')
if rc == 0:
logger.info("Connected")
mqttc.subscribe('test', 0)
else:
logger.info(rc)
def on_message(mqttc, obj, msg):
logger.info(msg.topic+" "+str(msg.qos)+" "+str(msg.payload))
mqttc = mqtt.Client("mqttpy")
mqttc.on_message = on_message
mqttc.on_connect = on_connect
As well as full stack trace:
ERROR 2014-06-03 15:14:57,285 wsgi.py:262]
Traceback (most recent call last):
File "/Users/cbarnes/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 239, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "/Users/cbarnes/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 298, in _LoadHandler
handler, path, err = LoadObject(self._handler)
File "/Users/cbarnes/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 84, in LoadObject
obj = __import__(path[0])
File "/Users/cbarnes/code/ignite/tank-demo/appengine-flask-demo/main.py", line 24, in <module>
mqttc = mqtt.Client("mqtthtpp")
File "/Users/cbarnes/code/ignite/tank-demo/appengine-flask-demo/lib/paho/mqtt/client.py", line 403, in __init__
self._sockpairR, self._sockpairW = _socketpair_compat()
File "/Users/cbarnes/code/ignite/tank-demo/appengine-flask-demo/lib/paho/mqtt/client.py", line 255, in _socketpair_compat
listensock.bind(("localhost", 0))
File "/Users/cbarnes/google-cloud-sdk/platform/google_appengine/google/appengine/dist27/socket.py", line 222, in meth
return getattr(self._sock,name)(*args)
File "/Users/cbarnes/google-cloud-sdk/platform/google_appengine/google/appengine/api/remote_socket/_remote_socket.py", line 668, in bind
self._SetProtoFromAddr(request.mutable_proxy_external_ip(), address)
File "/Users/cbarnes/google-cloud-sdk/platform/google_appengine/google/appengine/api/remote_socket/_remote_socket.py", line 632, in _SetProtoFromAddr
proto.set_packed_address(self._GetPackedAddr(address))
File "/Users/cbarnes/google-cloud-sdk/platform/google_appengine/google/appengine/api/remote_socket/_remote_socket.py", line 627, in _GetPackedAddr
AI_NUMERICSERV|AI_PASSIVE):
File "/Users/cbarnes/google-cloud-sdk/platform/google_appengine/google/appengine/api/remote_socket/_remote_socket.py", line 338, in getaddrinfo
canonical=(flags & AI_CANONNAME))
File "/Users/cbarnes/google-cloud-sdk/platform/google_appengine/google/appengine/api/remote_socket/_remote_socket.py", line 211, in _Resolve
canon, aliases, addresses = _ResolveName(name, families)
File "/Users/cbarnes/google-cloud-sdk/platform/google_appengine/google/appengine/api/remote_socket/_remote_socket.py", line 229, in _ResolveName
apiproxy_stub_map.MakeSyncCall('remote_socket', 'Resolve', request, reply)
File "/Users/cbarnes/google-cloud-sdk/platform/google_appengine/google/appengine/api/apiproxy_stub_map.py", line 94, in MakeSyncCall
return stubmap.MakeSyncCall(service, call, request, response)
File "/Users/cbarnes/google-cloud-sdk/platform/google_appengine/google/appengine/api/apiproxy_stub_map.py", line 328, in MakeSyncCall
rpc.CheckSuccess()
File "/Users/cbarnes/google-cloud-sdk/platform/google_appengine/google/appengine/api/apiproxy_rpc.py", line 156, in _WaitImpl
self.request, self.response)
File "/Users/cbarnes/google-cloud-sdk/platform/google_appengine/google/appengine/ext/remote_api/remote_api_stub.py", line 200, in MakeSyncCall
self._MakeRealSyncCall(service, call, request, response)
File "/Users/cbarnes/google-cloud-sdk/platform/google_appengine/google/appengine/ext/remote_api/remote_api_stub.py", line 234, in _MakeRealSyncCall
raise pickle.loads(response_pb.exception())
RuntimeError: error('illegal IP address string passed to inet_pton',)
INFO 2014-06-03 15:14:57,291 module.py:639] default: "GET / HTTP/1.1" 500 -
Thanks!
You're trying to connect to host test and port 0 where typically you should use localhost and 1883
See the getting started example here:
https://pypi.python.org/pypi/paho-mqtt/0.9#usage-and-api
I am trying to access linkedin API using python code. Here's the code that I am running on my windows machine:
from linkedin import server
import webbrowser
API_KEY = "<API_KEY>"
API_SECRET = "<API_SECRET>"
application = server.quick_api(API_KEY, API_SECRET)
I am executing these statements one-by-one in the console, but when I execute server.quick_api(API_KEY, API_SECRET), I receive the following error:
>>> application = server.quick_api(API_KEY, API_SECRET)
https://www.linkedin.com/uas/oauth2/authorization?scope=r_basicprofile%20rw_nus%20r_network%20r_contactinfo%20w_messages%20rw_groups%20r_emailaddress%20r_fullprofile&state=0b0290ff6e51e14c5409434a6e4bf52f&redirect_uri=http%3A//localhost%3A8000/&response_type=code&client_id=<API_KEY>
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\IPython\core\interactiveshell.py", line 2731, in run_code
exec code_obj in self.user_global_ns, self.user_ns
File "<ipython-input-9-eb867f0fb231>", line 1, in <module>
application = server.quick_api(API_KEY, API_SECRET)
File "C:\Users\sony\AppData\Roaming\Python\Python27\site-packages\linkedin\server.py", line 24, in quick_api
_wait_for_user_to_enter_browser(app)
File "C:\Users\sony\AppData\Roaming\Python\Python27\site-packages\linkedin\server.py", line 38, in _wait_for_user_to_enter_browser
httpd = BaseHTTPServer.HTTPServer(server_address, MyHandler)
File "C:\Python27\lib\SocketServer.py", line 419, in __init__
self.server_bind()
File "C:\Python27\lib\BaseHTTPServer.py", line 108, in server_bind
SocketServer.TCPServer.server_bind(self)
File "C:\Python27\lib\SocketServer.py", line 430, in server_bind
self.socket.bind(self.server_address)
File "C:\Python27\lib\socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
error: [Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions
I get a url which I understand I am supposed to get, but what's the cause of this error?
Also, when I paste the url in the browser, it takes me to linkedin page and asks for my credentials which it never accepts (I am sure I am entering the correct credentials). It always shows:
"HTTP Error 404. The requested resource is not found."
I am otherwise able to login to linkedin using the same credentials.