Getting "Method Not Allowed" when using fastapi - python

I am trying to run the following code but I am getting a {"detail":"Method Not Allowed"} error when I open http://localhost:8000/predict.
The code:
from fastapi import FastAPI
app = FastAPI()
#app.post("/predict")
def predict_(request: str):
return {"message": 'Hellooo!'}
What's the problem with my code?
I searched online for similar examples but I got the same error! For example this one: https://codehandbook.org/post-data-fastapi/

It's because when you open the page in a browser, it makes a GET request, but your app only handles POST. Change to #app.get(...), and you should be able to see it in a browser. Or, navigate to http://localhost/docs and use the interactive documentation to test it as it is.

Related

How do I redirect from one flask app to another flask app with url parameters

I have a Python application in which for one specific API, I am trying to redirect it to another API present in another Flask application. To achieve this, I am using the below code:
`
#app.route('/hello')
def hello_name(name):
return redirect("http://localhost:8000/hello", 302)
`
Now, if I try to access my API by appending query parameters like http://localhost:6000/hello?name=Sidharth, it should be redirected to http://localhost:8000/hello?name=Sidharth. Can I get an advice on how this can be done?
I looked online and found that most of the posts are advising usage of url_for() but since I don't want to redirect to another view, I don't think url_for() will be beneficial in my case. With the code that I have written now, the query parameters are not being added to the redirected url.
Try to use HTTP status code 307 Internal Redirect instead of 302 like below:-
#app.route('/hello/')
def hello_name(name):
return redirect(url_for('http://localhost:8000/hello', args1=name), code=307)

Publish a script online

I have a Python script written up and the output of this script is a list.
Right now I need to get it online and make it accessible to others. I looked at Django , but then I realized that it may be kind of hard to create the UI. Is there any simple way to create a UI in Django and map it to an existing Python script.
Right now I using nltk, numpy, sqlite3 and things like that. Or is there a simpler way by which I can proceed?
In your case, Django is redundant.
You can use something smaller, Flask or maybe Aiohttp.
For example, all you need in aiohttp:
basic hmtl template
handler for one url (here you will call your script)
aiohttp webserver
The main idea:
Your server catch some url (for example /),
start your script, receives result,
respond with your html template (also render script result in it).
You can try creating a flask App.
Just do a pip install Flask and try the code below
from flask import Flask
import flask
import json
from flask import Response
app = Flask(__name__)
#app.route('/test',methods=['GET'])
def test():
'''
GET: Receives the request in /test route and returns a response containing {"response": [1,2,3]}
'''
my_list = [1,2,3]
resp = Response(response=json.dumps({"response": my_list}), status=200, mimetype='application/json')
return resp
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=8082)
Then to test your app from your browser accessing
localhost:8082/test
or also through some app like postman
I would suggest looking into something like React for creating the UI. This way your UI would only make calls to your Flask server.

Postman, Python and passing images and metadata to a web service

this is a two-part question: I have seen individual pieces discussed, but can't seem to get the recommended suggestions to work together. I want to create a web service to store images and their metadata passed from a caller and run a test call from Postman to make sure it is working. So to pass an image (Drew16.jpg) to the web service via Postman, it appears I need something like this:
For the web service, I have some python/flask code to read the request (one of many variations I have tried):
from flask import Flask, jsonify, request, render_template
from flask_restful import Resource, Api, reqparse
...
def post(self, name):
request_data = request.get_json()
userId = request_data['UserId']
type = request_data['ImageType']
image = request.files['Image']
Had no problem with the data portion and straight JSON but adding the image has been a bugger. Where am I going wrong on my Postman config? What is the actual set of Python commands for reading the metadata and the file from the post? TIA
Pardon the almost blog post. I am posting this because while you can find partial answers in various places, I haven't run across a complete post anywhere, which would have saved me a ton of time. The problem is you need both sides to the story in order to verify either.
So I want to send a request using Postman to a Python/Flask web service. It has to have an image along with some metadata.
Here are the settings for Postman (URL, Headers):
And Body:
Now on to the web service. Here is a bare bones service which will take the request, print the metadata and save the file:
from flask import Flask, request
app = Flask(__name__)
# POST - just get the image and metadata
#app.route('/RequestImageWithMetadata', methods=['POST'])
def post():
request_data = request.form['some_text']
print(request_data)
imagefile = request.files.get('imagefile', '')
imagefile.save('D:/temp/test_image.jpg')
return "OK", 200
app.run(port=5000)
Enjoy!
Make sure `request.files['Image'] contains the image you are sending and follow http://flask.pocoo.org/docs/1.0/patterns/fileuploads/ to save the file to your file system. Something like
file = request.files['Image']
file.save('./test_image.jpg')
might do what you want, while you will have to work out the details of how the file should be named and where it should be placed.

Flask URL routes using blueprint are not working, return 404 http code

I am facing a problem with flask url routing; it seems routes are not working as expected.
Under project/src/views.py, I have the following sample routes
from flask import (Flask,request,jsonify,Blueprint)
my_view = Blueprint('my_view', __name__)
#my_view.route('/',methods=("GET",))
#my_view.route('/index',methods=("GET",))
def index():
....
<return response code here>
#my_view.route("/key/<inp1>/<inp2>", methods=("POST","GET"))
def getKey(inp1=None, inp2=None):
....
<return response code here>
Now, under project/src/app.py, I have the following code
from ../src.views import my_view
my_app = Flask("myappname")
my_app.register_blueprint(my_view)
my_app.run(debug=True,host=APP_IP,port=APP_PORT)
Now, when I access the URL http://ip:port/index or http://ip:port/key... with valid parameters, it returns 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." I believe mentioned routes are not working.
The first issue spotted is with your methods parameter. It expects a list/tuple but you're passing a string ('GET'). Change to methods=('GET', ). Note the comma after 'GET' here. Or to avoid potential confusion in the future, use methods=['GET']
The second issue is the way you're import my_view in app.py. Since views.py and app.py are in the same directory, and you're starting your flask app inside that directory, you can just do:
from views import my_view
However you should look into structuring your app as a Python Package
The third issue is a missing from flask import Flask. Maybe you overlooked this when you posted your code.
I tested your code with the above fixes and it works like it should.
EDIT: Thanks to #dirn for pointing out that tuples are accepted for methods parameter.

AssertionError: Request global variable is not set

I know this is a duplicate question but by referring previous answers i couldn't find the solution yet.
I am using Google report api to fetch logs.
Please refer this link: https://developers.google.com/admin-sdk/reports/v1/libraries
Everything goes well and I am able to generate authorize URL using scope,client id etc.
But I am not able to redirect user to URL to fetch "code" from authorize URL.
I tried using webapp2 script but throws error = AssertionError: Request global variable is not set.
Here is the code I am using for redirection:
import webapp2
class MainPage(webapp2.RequestHandler):
def get(self):
import ipdb;ipdb.set_trace()
path='my authorize url path'
return self.redirect(path) #throws error on this line
a1=MainPage() #object to call class
a2=a1.get() #call method of class
Where i am going wrong ? If webapp2 having standard bug for self.redirect, then which other framework can help to to perform same operation?
If i use app = webapp2.WSGIApplication([('/', MainPage)]) instead of creating objects then it doesnt even call get(self) function.
Any help would be appreciated.
Thanks.

Categories