Flask requests not working when application is deployed - python

I deployed a flask application in Windows Server 2016 on IIS. Everything was working fine, then I updated windows and now, I'm unable to use requests.get() when deployed.
Here is a simple code:
from flask import Flask
from flask_cors import CORS
from flask import request
import requests
app = Flask(__name__)
CORS(app, resources={r"/*": {"origins": "*"}}, send_wildcard=True)
#app.route("/")
def hello():
r = requests.get('http://google.com')
return r.text
if __name__ == "__main__":
print ("\nAttempting to start server ...")
app.run(threaded = True, port=5052)
When I run it, it browser will hang for 30s or so, and then returns a 500 error.
The server has access the internet: i can browse, use pip and I'm even able to do requests from the python command line or as a stand alone program, but not when it's deployed.
I have tried headers, cors, played with pratically all possible settings. I have no idea why it doesn't work anymore.

can u change your protocol as https..It works fine for me..:) I too spent nearly one hour for trying out all possibilities.
Sorry for turning out this to be simple :)
Interesting this is my first solution on stack overflow..

Related

I can't connect my code to my local host webserver from terminal

I'm trying to run my code from the terminal to my local host using python3 command but its not running on the server for some reason. Can anyone help?
Here is my code to connect to web server.
from flask import Flask
from flask import request
from flask import Response
import keywordnum
app_first = Flask(__name__)
#app_first.route("/")
def key():
word=request.args.get('word')
len=keywordnum.count(word)
reply=str(len)
r= Response(response=reply, status=200)
return r
if__name__=='__main__'
app_first.run(host="0.0.0.0",port=4000)
Check your indentation, python is strict with it. The following line
if__name__=='__main__'
should be rewritten as follows:
if __name__=='__main__':
Indentation in python allows for a clearer code.

How to invoke/run a Python script using a web URL?

I have a Python script that pulls data from a 3 rd party API. Currently this Pyhton script is automated on server side.
There are few instances where I have to toggle the script manually for new data updates. For the manual toggle I have to login to the server each time and run it from command line. Is there a way where I can create web url or something similar and just run that URL to make that script run from the browser address bar.
One approach you could take is to use Flask, which is a minimal web framework. Here's an example of how you could use it:
from flask import Flask
from your_script import your_func
app = Flask(__name__)
#app.route('/run')
def run_command():
your_func()
return 'Executed your function!'
if __name__ == '__main__':
app.run(debug=False, port=8080)
If you run this code you'd get a web server running on port 8080 that executes your function when you access the url. Here's a tutorial in the Flask documentation to get you started.
I think the easiest way to do this is by using Flask.
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
# your code here
return 'Hello, World!'

Python Flask app route is not working well

I tried to find a solution for my problem in other questions but I couldn't.
I downloaded the python flask and made my first flask app and it ran fine.
Here is the code:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def index():
return "Hello, world!"
When I ran my second file where I had added an app.route ("/ david") and followed the same procedure again, refreshed it and nothing changed.
That is to say, I was going to / david and I get an URL error
Here is my second file
from flask import Flask
app = Flask(__name__)
#app.route("/")
def index():
return "Hello, world!"
#app.route("/david")
def david():
return "Hello, David!"
I tried the same with other files which have some added routes and the result is the same as the first file
Thanks for your answers, I hope to solve my problem.
You did not run the app. What you did is just create a structure for flask, but did not start the server.
Just add:
app.run()
To the bottom of the file and it will work. It will with start the flask server at http://localhost:5000.
By default, flask runs on port 5000.
It can be changed by:
app.run(host="0.0.0.0", port=xxxx)
0.0.0.0 means it accepts request from anywhere on the port specified.
Make sure you have all the permissions and nothing else is running if you want it to run on port 80.
Hope this helps. Good luck.
I had the same issue. Try first by restarting your IDE; this worked for me. If that doesn't work, try clearing your ports for Windows:
Open Task manager
Click on the “Processe” tab
Enable the "PID" column: View -> Select Columns -> Check the box for PID
Find the PID (in your case, 5000 - flask default port) and click “END PROCESS"

Python script with flask server takes too long to exit on Windows

I'm new to Python.
As a part of a project I'm trying to deploy a Flask server locally, through the Windows command line.
My Python version is 3.6.0.
The code:
from flask import Flask
app = Flask(__name__)
#app.route('/') def index():
return '<h1>Hello World!</h1>'
if __name__ == "__main__":
app.run()
The problem:
It's about killing the script as it runs. Launching this script with python deploy.py and hitting CTRL+C shuts it off.
BUT - if I hit access that '/' route via the browser once or more, and a moment later try to kill the script in the same manner, then it would take about 10 seconds of nothing until it responds and is finally killed.
Why is this happening? How can I shut the server off immediately each time for continuous and quick development?
Thanks!!
Well if your goal is continuous and quick development, then you can change flask's configuration.
Best solution for your problem would be setting the DEBUG setting to True. If DEBUG is set to True, then flask will automatically reload the server on code changes.
There are a few ways to do this but the easiest one(because you said you are a beginner) is to pass the debug argument to app.run()
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return '<h1>Hello World!</h1>'
if __name__ == "__main__":
app.run(debug=True)

arduino yun uhttpd flask setup

I'm trying to set up python and flask on the arduino yun. I've managed to run python files via the /etc/config/uhttpd configuration file:
...
list interpreter ".py=/usr/bin/python"
...
The default path for the website's root is: /www in which I've placed a soft link (apps) to the sd card. So now I can run python programs: http://[ip arduino]/apps/helloworld.py
And when I make my first helloflask.py program and run that via python helloflask.py I can see the result at: http://[ip arduino]:5000
But now I want to configure the uhttpd mini webserver (which is capable to exchange information via CGI) to use the flask setup. The URI: http://flask.pocoo.org/docs/deploying/cgi/#server-setup shows some instructions... but I just don't get it. I've made a directory ../apps/uno in which I've placed a __init__.py file with the following content:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "He Flask!"
In the apps dir I've put a file: cgi.py with this content:
from wsgiref.handlers import CGIHandler
from uno import app
CGIHandler().run(app)
Now I when I browse: http://[ip arduino]/cgi.py get a server error occured, contact the administrator (I think this is the CGI interface from uhttpd).
I just don't grasp the CGI configuration for Flask/uhttpd
I looked into this too and got a little further, I was able to setup a simple hello world but once I tried to do something non-trivial I ran into a big issue that uhttpd doesn't support URL rewriting/aliasing. This means your flask app can only be served at the URL of its .py file instead of at a root like http:// (arduino IP) /flaskapp/. None of the routes inside the app will be visible and makes the whole thing unusable.
However, instead of trying to force flask into uhttpd I had great success running the built in server that flask provides. Take a look at this guide I wrote up that uses flask to serve data from a Yun: https://learn.adafruit.com/smart-measuring-cup/overview
The thing to do is add a call to app.run when the script is run, for example make your flask app look like:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "Hello Flask!"
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True, threaded=True)
Then log in to the Yun and run the script using python. Flask's built in server should start serving the app on http:// (arduino IP) :5000/. Make sure to include the host='0.0.0.0' as it's required to listen on the Yun's external network interface. You probably also want debug=True so there are better error messages (and live reloading of the server when the code changes), and I found threaded=True helps because the default server only handles one connection at a time. The Yun is a relatively slow processor so don't expect to service a lot of concurrent requests, however it's quite capable for providing a simple REST API or web application for a few users.
If you want this server to always run on bootup, edit the /etc/rc.local file to include a call to python and your script.

Categories