How do I upload images with Flask and requests? - python

I am trying to make an API that when a POST request is made, it will accept images and then save them, and if a GET request is made then it will send back a URL to where you'd be able to download that image. How would that be possible?
This is the Flask app running on localhost for testing:
from flask import Flask, send_file
app = Flask(__name__)
#app.route("/upload_image/<filename>", methods=["POST"])
def upload_image(filename):
# receive the image here
# ...
#app.route("/get_image", methods=["GET"])
def get_image():
filename = "encoded_image.png"
return send_file(filename, mimetype="image/png")
if __name__ == "__main__":
app.run(host="localhost", port=5000)
I think sending the image is easy but I don't know how to go about receiving it and using requests to send it.
This is the idea behind the main code:
import requests
option = input()
if option == "get image":
print("Download the image at: https://localhost:5000/get_image")
elif option == "upload image":
post = requests.post("https://localhost:5000/upload_image/encoded_image.png")
i don't want the images to change names. I always want to send the file encoded_image.png and receive it, because I want it to be overwritten when the POST is made. This is for a discord bot but that doesn't really affect anything, I just thought I'd mention it. Thanks in advance :)

Related

Getting camera input from user in Flask

I have a problem. I'm making a Flask application that requires camera input, which is sent to opencv, and then I process it and return an image. I have no problem with the streaing. My issue here is the fact that I need to access the user's webcam, and give the information to Flask so it can process the image, and THEN return it. To do this, I need access to the user's webcam. I imagine something like this:
main.py
from flask import Flask, request, render_template
from myapp import process #Import function to process image
app = Flask(__name__)
#app.route("/webcam", methods=["GET", "POST"])
def camera():
if request.method == "POST":
image = request.get_json()['image']
result = process(image) #Process image
return result
else:
return('camera.html') #Return camera site
#Other code/functions...
Then in the html file, I'd have a <script> tag with the script to send a post request with the image.
(If there is a better way to do this, tell me.)
I don't know how to get the image to the user, though, in a way that OpenCV can process it.

Web server in python for responding to GET and POST

I want to create web server, and listen now.
Server must have different functions for each endpoint (and method).
I want to get (e.g. to variable) parameters (and data if POST)
Respond to get (and POST if its possible)
Respond in JSON
Someone can help me with this?
PS: I will be run it on Heroku, and send requests to it via Roblox's HttpService
Below see examples of each of your requirements using the Flask lightweight web framework.
After that is a link to a short description of how to deploy to Heroku.
# app.py
from flask import Flask
from flask import request, render_template
app = Flask(__name__)
#app.route('/test-get-request-parameters')
def test_get_request_parameters():
# 1. different function per endpoint
# 2. GET parameter to variable
# 3. respond to GET
var = request.args.get('some_request_variable')
return render_template('hello_world.html')
#app.route('/test-post-method',methods=['POST'])
def test_post_method():
# 2. receive POST data
# 3. respond to POST
print(request.get_json())
return 'hello, world!'
#app.route('/test-get-or-post', methods=['GET','POST'])
def test_get_or_post():
# 4. respond in JSON
if request.method == 'POST':
d = {'hello':'world'}
return d # this will be JSON response
return render_template('test.html')
To deploy to Heroku you need a Procfile with something like this in it:
web: gunicorn app:app
And you can follow these instructions: https://devcenter.heroku.com/articles/getting-started-with-python

Python Flask local server not updating

I am starting to learn Flask, so I am a noob in this stuff, but I have ran out of ideas to implement, that is why I came here to ask. I have python script that makes a GET request to the API and it returns me a QRcode, after that I get the QRcode and add it to my html, everything works fine.
But I have this code checking for the JSON response that the API gives me, it haves three responses: "loading", "authenticated" & "got qr code".
req = requests.get('this is the link with my API token')
json_content = req.content
# parsed JSON content, ready to use
parsed_json = json.loads(json_content)
#app.route("/")
def index():
if parsed_json["accountStatus"] == "loading":
print(parsed_json["accountStatus"])
print(req.status_code)
return render_template("loading.html")
if parsed_json["accountStatus"] == "got qr code":
print(parsed_json["accountStatus"])
str_parsed_json = yaml.safe_load(parsed_json["qrCode"])
print(req.status_code)
return render_template("qrcodePage.html", str_parsed_json=str_parsed_json)
if parsed_json["accountStatus"] == "authenticated":
print(parsed_json["accountStatus"])
print(req.status_code)
return render_template("index.html")
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000, debug=True)
The response I am getting is a 200
I have searched all over the internet to see if someone else has the same issue as me, but I haven't found one person with this problem.
I have tried restarting the following
Restart my local server
Making True the debug thing in the app.run()
Check in PostMan the server response but it always return me the expected result, but changes are not seen in the page.
The only way it seems to work is when I make some changes to my code, and restart the server, that is when I can refresh the page and redirect me to the expected template file.
Thanks in advance.
Move your requests.get and all subsequent object based on that inside your index():
#app.route("/")
def index():
req = requests.get('this is the link with my API token')
json_content = req.content
# parsed JSON content, ready to use
parsed_json = json.loads(json_content)
if parsed_json["accountStatus"] == "loading":
print(parsed_json["accountStatus"])
return render_template("loading.html")
... rest of your code
Currently your requests is not being refreshed past the point of your server starting. But if you move it inside your #app.route("/") each time you visit the site's root page, it will do a new requests.get() to refresh your data.

Post API-- what are the steps that need to be followed once the code is created so that I can add data into a txt file through this API

I am new to API, and get a tasks of creating POST API. I have created a code somehow.
I want to add data to the hello.txt through post API, So how will I do it?
Here is my code:
import flask
from flask import request, jsonify
app = flask.Flask(__name__)
app.config["DEBUG"] = True
#app.route('/api/v1/resources/messages', methods = ['POST'])
def api_message():
if request.headers['Content-Type'] == 'text/plain':
return "Text Message: " + request.data
elif request.headers['Content-Type'] == 'application/octet-stream':
return "Binary message written!"
elif request.headers['Content-Type'] == 'application/json':
f = open('F:\Asif_Ahmed\Projects\api\hello.txt',"w")
f.write(request.data)
f.close()
return "JSON Message: " + json.dumps(request.json)
else:
return "415 Unsupported Media Type ;)"
app.run()
from flask import Flask, jsonify, render_template, request #import flask library
from flask_basicauth import BasicAuth # import flask library for create basic authentication if needed
from flask_cors import CORS # import flask library Cross-Origin Resource Sharing that is a mechanism that uses additional HTTP headers to tell a browser to let a web application running at one origin (domain) have permission to access selected resources from a server at a different origin
app = Flask(__name__)
CORS(app) #set-up cors for my app
#if you want use basic authentication you need set-up username and password
app.config['BASIC_AUTH_USERNAME'] = 'admin'
app.config['BASIC_AUTH_PASSWORD'] = 'password'
basic_auth = BasicAuth(app)#set-up username and password for my app but in this case I'm not specifying yet in which API use them
#app.route('/api/v1/resources/add_messages', methods=['POST'])#create my POST api
#basic_auth.required# set-up basic authentication for this API, comment out if not needed
def update_credential ():
json_credential=request.get_json()#get the JSON sent via API
print (json_credential["message"])#get the node "message" of my JSON
###########
#code to write in your file, you need write the json_credential["message"]
###########
return ("ok")
if __name__ == '__main__':
app.run(host='0.0.0.0', port=1024, threaded=True)#start my flask app with local_host IP and specific port, if you don't specify the port it will run in the default port
In this case the JSON Input should be:
{"message":"your text"}
Please let me know if something is not clear, I even try this code on my local and the JSON is passed without problems.....
So you need run your python script and see that the API is running, if you had no JSON to send and was just a simple API that give back information you should have used even Chrome but in this case that you need send some JSON data I would advice you to use Postman.
See screenshot example:

Moving a file using a python web service [duplicate]

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.

Categories

Resources