The answer that I found on the web is to use request.args.get. However, I cannot manage it to work. I have the following simple example:
from flask import Flask
app = Flask(__name__)
#app.route("/hello")
def hello():
print request.args['x']
return "Hello World!"
if __name__ == "__main__":
app.run()
I go to the 127.0.0.1:5000/hello?x=2 in my browser and as a result I get:
Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
What am I doing wrong?
The simple answer is you have not imported the request global object from the flask package.
from flask import Flask, request
This is easy to determine yourself by running the development server in debug mode by doing
app.run(debug=True)
This will give you a stacktrace including:
print request.args['x']
NameError: global name 'request' is not defined
http://localhost:5000/api/iterators/opel/next?n=5
For something like the case before
from flask import Flask, request
n = request.args.get("n")
Can do the trick
Related
I am trying to host a flask server from my windows computer so I can access it from external devices
I am using Flask/Python and have already tried a few things but can't get it to work
Tried running it on 0.0.0.0, port 33, 5000, etc. but I still can't access it this way
from flask import Flask, request, abort
app = Flask(__name__)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=33)
When I then run the file I get:
Running on http://0.0.0.0:33/ (Press CTRL+C to quit)
But it isn't even running there, nor on any other way I can access it
I expect to be able to access my flask application and send requests to it by using my public IP address
What can I do here to make it work?
You have missed an important line in your code:
After the line
app = Flask(__name__)
You have to write the line:
#app.route('/')
We use the route() decorator to tell Flask what URL should trigger our function.
And then define a function that will tell what task to be performed in the web app hosted in the respective address.
The function might look something like this:
def hello_world():
return 'Hello, World!'
The complete code then will look like:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run(host='0.0.0.0', port=33)
Hope this helps.
I'm trying to create a python Flask REST web API. Since Flask development server is not suitable for production, I tried to use cherrypy application server.
Following is the Flask app I tried to expose via cherrypy
from flask import Flask,request
from flask_restful import Api,Resource, reqparse
app= Flask(__name__)
api = Api(app)
class Main (Resource):
def get(self):
return "Hello Flask"
if __name__ == '__main__':
api.add_resource(Main, "/testapp/")
app.run(debug=True)
Following is the cherrypy script I have created
try:
from cheroot.wsgi import Server as WSGIServer, PathInfoDispatcher
except ImportError:
from cherrypy.wsgiserver import CherryPyWSGIServer as WSGIServer, WSGIPathInfoDispatcher as PathInfoDispatcher
from stack import app
d = PathInfoDispatcher({'/': app})
server = WSGIServer(('127.0.0.1', 8080), d)
if __name__ == '__main__':
try:
server.start()
print("started")
except KeyboardInterrupt:
server.stop()
I have saved this script as "run.py" in my project directory. When I run this it doesn't show any error, which made me to thin this is correct.
But unfortunately I cant access this using the url
Theoretically, url for this API should be some thing like follow
http://127.0.0.1:8080/testapp/
But it throws 404 with the message
"The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again."
What am I doing wrong ?
The
api.add_resource(Main, "/testapp/")
in your file stack.py is not executed if the file is included from your run.py
as the condition
if __name__ == '__main__':
...
is not true (in the context of stack.py).
Moving the call to api.add_resource(...) to a position outside the if-main-condition (so it is always executed) should solve the issue.
My server.py is as follows,
from flask import Flask, jsonify, Response, redirect
import json
from UIAccess import UIAccess
app=Flask(__name__)
#app.route('/Hello/<username>')
def id_no(username):
id= obj.get_id(username)
return json.dumps(id)
if __name__ == '__main__':
obj=UIAccess()
app.run(threaded=True)
when I run the program and load the page using my browser I am able to view the output of 'id_no' but if I run the same program using twisted with the command,
twistd web --wsgi server.app
I get an internal server error, I am wondering whether this is the correct way to do this?
You only create obj if __name__ == '__main__', which it does not when you run with something besides python server.py. But the id_no view depends on obj being defined, so it fails. Move obj = UIAccess() out of the guard block.
Consider the following minimal working flask app:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def hello():
return "I am /"
#app.route("/api")
def api():
return "I am /api"
if __name__ == "__main__":
app.run()
This happily works. But when I try to make a GET request with the "requests" module from the hello route to the api route - I never get a response in the browser when trying to access http://127.0.0.1:5000/
from flask import Flask
import requests
app = Flask(__name__)
#app.route("/")
def hello():
r = requests.get("http://127.0.0.1:5000/api")
return "I am /" # This never happens :(
#app.route("/api")
def api():
return "I am /api"
if __name__ == "__main__":
app.run()
So my questions are: Why does this happen and how can I fix this?
You are running your WSGI app with the Flask test server, which by default uses a single thread to handle requests. So when your one request thread tries to call back into the same server, it is still busy trying to handle that one request.
You'll need to enable threading:
if __name__ == "__main__":
app.run(threaded=True)
or use a more advanced WSGI server; see Deployment Options.
I was following a Twilio tutorial on sending SMS through the API. I followed all the steps, however, I am receiving a 405 error. My code:
from flask import Flask
from twilio import twiml
import os
app = Flask(__name__)
#app.route('/sms', methods=['POST'])
def sms():
r = twiml.Response()
r.sms("This is awesome!")
return str(r)
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))
if port == 5000:
app.debug = True
app.run(host='0.0.0.0', port=port)
I am getting a 405 error (method not allowed), when calling my url, which looks like: http://my-url.herokuapp.com/sms, which is also associated like this to the twilio account. When I include 'GET', everything works, this is not according to tutorial however. Any hints?
Looking at the repository it seems that you will actually need to text to the number that Twillo is proxying for you. If you want to access the URL in your browser as well you will need to add 'GET' to the methods list (as you discovered).