Traceback (most recent call last) - Python - python

I am a very beginner in the flask environment..
this is main.py
from flask import Flask
from flask_restful import Api, Resource
app = Flask(__name__)
api = Api(app)
class Helloworld(Resource):
def get(self):
return {"data": "Hello QQ"}
api.add_resource(Helloworld, "/helloworld")
if __name__ == "__main__":
app.run(debug=True)
text.py file
import requests
BASE = "http://127.0.0.1:5000/"
response = requests.get(BASE + "Helloworld")
print(response.json())
When I was run text.py, had these error..
Please tell me the error and why it is?

The route in your code says "/helloworld" but you are doing "/Helloworld" in your requests call and I'm pretty sure that part of your URL is case sensitive, at least in this example.

Related

Python - access flask app context before serving requests

Usecase: I have a python flask app that runs background_function() before serving any requests on routes.
When I execute the flask app, I receive the error - RuntimeError: Working outside of application context. I receive the error since I try to get the application context before any request is served.
What is the best pythonic way to execute the background_function() in this example?
from flask import Flask
from download import Download
app = Flask(__name__)
app.config.from_pyfile('config.py')
# run backgroung function
Download.background_function()
#app.route('/')
def index():
return 'Welcome!'
if __name__ == '__main__':
app.run()
The config file
FILE_LOCATION = os.environ['FILE_LOCATION'] # "file/path/on/server"
# Many other variables are present in this file
The download file
from flask import current_app as app
class Download:
#staticmethod
def background_function():
file_path = app.config["FILE_LOCATION"]
# code to download file from server to local
return
Try this:
from flask import Flask
from download import Download
app = Flask(__name__)
#app.route('/')
def index():
return 'Welcome!'
if __name__ == '__main__':
Download.background_function()
app.run()
the download file
from flask import current_app as app
class Download:
#staticmethod
def background_function():
print("testing")
given output:
testing
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
As you can see, the function runs first and prints testing and then runs the application.

i have a problem whith flask and python the problem is

from flask import Flask
app = flask(__name__)
#app.route("/")
def home():
return "Hello world"
if __name__ == "__main__":
app.run()
and in termianl send me this error
Traceback (most recent call last):
File "C:\Users\xd\Desktop\python-anashe\index.py", line 3, in <module>
app = flask(__name__)
NameError: name 'flask' is not defined
You're importing the name Flask from the module flask.
That means you'll need (note the capital F)
app = Flask(__name__)
instead of lower-case app = flask(__name__).

i've got a problem with flask using app.route()

i'm trying to create a web server with Flask python library but there is something wrong because it keeps giving me the error when i run the file.
here is the code:
from flask import Flask, app
app = Flask(__name__)
#app_route("/")
def main():
return('welcome to my flask page')
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port="8090")
here is the error:
Traceback (most recent call last):
File "c:\Users\User\Desktop\Simone\Simone\Js Course\Python Web Server\web server.py", line 5, in <module>
#app_route("/")
NameError: name 'app_route' is not defined
Help me please!!!
The app you're importing from flask isn't what you expect (it's a module within Flask that contains flask code). You need to create an instance of Flask, and apply the route to that.
from flask import Flask
app = Flask(__file__) # add this
#app.route('/') # and use app.route instead of app_route
...

How to send a dill byte object to restful api

I am using flask restful on the server and need to use dill in order to dump a function to a binary and send it to the server
I am using this code to create the request
import inspect
import dill
import requests
def f():
a = 1
v = 2
return 1
b = dill.dumps(f, protocol=None)
requests.post("http://localhost:5000/server", data={"func": b})
and using this code on the server
from flask_restful import Resource, Api, reqparse
from flask import app
from flask import Flask
import dill
app = Flask(__name__)
api = Api(app)
class S(Resource):
def post(self):
parser = reqparse.RequestParser()
parser.add_argument("func", type=bytes, location="form")
try:
args = parser.parse_args()
print(dill.loads(args["func"])())
print(1)
except Exception as e:
print(e)
print(2)
api.add_resource(S, '/server')
if __name__ == '__main__':
app.run(debug=True, host="0.0.0.0", port=5000)
I keep geting errors about request that the server could not understand,
I tried marking the type as bytes, bytearray, str
I tried sending it in data, json and params
all without any luck.
What am i missing here?

Flask with Waitress - get request headers returns None

Using just the Flask server with Python, the following get request works:
from flask import Flask, request
app = Flask(__name__)
class Result(Resource):
def get(self):
image_id = request.headers.get('image_id')
api.add_resource(Result, '/results')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=int(os.getenv('PORT', 5000)))
However, using Waitress, the following does not work (image_id is None):
from waitress import serve
from flask import Flask, request
app = Flask(__name__)
class Result(Resource):
def get(self):
image_id = request.headers.get('image_id')
api.add_resource(Result, '/results')
if __name__ == '__main__':
serve(app, host="0.0.0.0", port=int(os.getenv('PORT', 5000)))
POST and other GET requests work fine, it's just GET with headers that doesn't work. Anyone have any ideas?
I had the same issue, after searching around I found this issue on GitHub. Apparently it is a security feature and you should not use _ in your header. So you should rename your header to image-id or something else without a _ character for it to work.

Categories

Resources