Postman stuck when sending post request to Flask on second time - python

I am creating an application where I have to read images from a POST call in Flask. I am using the instructions as provided in this question for setting Postman. My Flask code looks like follows:
from flask import Flask, request, session
import cv2
# Initialize the Flask application
app = Flask(__name__)
#app.route('/predict', methods=['POST'])
def predict():
r = request
# convert string of image data to uint8
# decode image
imagefile = request.files.get('imagefile', '')
imagefile.save('temp.jpg')
img = cv2.imread('temp.jpg')
cv2.imshow("img", img)
cv2.waitKey()
cv2.destroyAllWindows()
return ("SUCCESS")
if __name__ == '__main__':
app.run(debug=True, port=5000)
The program runs fine on calling it for the first time and displays the image correctly, but when I try to call it again without rerunning the python code it gets stuck on sending request. Please let me know what I am doing wrong and how to correct it. I am using Ubuntu 18.04 with the Postman application for Linux.
EDIT
As suggested by #MaxTryk I tried adding breakpoints to find the culprit and it is the image showing section.
cv2.imshow("img", img)
cv2.waitKey()
cv2.destroyAllWindows()
However, I still don't have any ideas why these statements are causing the second request to hang, so if you know any way to correct it please let me know.

If rerunning the python code solves the issue, the problem must be the code, not Postman - I'd suggest to debug by placing breakpoints to see where the execution hangs up.

Related

Flask request.form too slow when getting image from android studio

I am running my Flask app on Ubuntu VPS (linode) as server. I am capturing image from android studio sending it to flask server to get response. Image is being sent as base64 string from android studio.
But the response is too slow when using request.form.to_dict(). Both ubuntu vps and android app are running on different IP.
I've put timestamps on different processes and found this request.form.to_dict() is the problem taking around 22 to 35 secs.
I am also using image compressing techniques on my android studio code but still too much time.
Tried on gunicorn with nginx but same.
threaded = True
Images are of around 400kb to 500kb size.
Kindly help me to figure out this issue.
Below is my flask code:
#app.route('/predict', methods=['POST', 'GET'])
def predict():
if request.method == 'POST':
file = request.form.to_dict()['upload'] # 22.2491 sec
b64_string = file
image = imread(io.BytesIO(base64.b64decode(b64_string))) #0.0023 sec
image = cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB) # 0.000171 sec
.....
.....
.....
sending the images in base64 format is not the recommended method, you should try to send the photo via a multipart request.
Look here to see how to send an image from android in multipart form data (if you are using java).
If you send the images via multipart form data you will then be able to access them on flask using the method request.files['my_file_name']:
#app.route('/upload', methods=['POST'])
def upload_file():
my_file = request.files['my_file_name']:

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.

Trading view alerts to trigger market order through python and Oanda's API

I'm trying to trigger a python module (market order for Oanda) using web hooks(from trading view).
Similar to this
1) https://www.youtube.com/watch?v=88kRDKvAWMY&feature=youtu.be
and this
2)https://github.com/Robswc/tradingview-webhooks-bot
But my broker is Oanda so I'm using python to place the trade. This link has more information.
https://github.com/hootnot/oanda-api-v20
The method is web hook->ngrok->python. When a web hook is sent, the ngrok (while script is also running) shows a 500 internal service error and that 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.
This is what my script says when its running (see picture);
First says some stuff related the market order then;
running script picture
One thing I noticed is that after Debug it doesn't say Running on... (so maybe my flask is not active?
Here is the python script;
from flask import Flask
import market_orders
# Create Flask object called app.
app = Flask(__name__)
# Create root to easily let us know its on/working.
#app.route('/')
def root():
return 'online'
#app.route('/webhook', methods=['POST'])
def webhook():
if request.method == 'POST':
# Parse the string data from tradingview into a python dict
print(market_orders.myfucn())
else:
print('do nothing')
if __name__ == '__main__':
app.run()
Let me know if there is any other information that would be helpful.
Thanks for your help.
I fixed it!!!! Google FTW
The first thing I learned was how to make my module a FLASK server. I followed these websites to figure this out;
This link helped me set up the flask file in a virtual environment. I also moved my Oanda modules to this new folder. And opened the ngrok app while in this folder via the command window. I also ran the module from within the command window using flask run.
https://topherpedersen.blog/2019/12/28/how-to-setup-a-new-flask-app-on-a-mac/
This link showed me how to set the FLASK_APP and the FLASK_ENV
Flask not displaying http address when I run it
Then I fixed the internal service error by adding return 'okay' after print(do nothing) in my script. This I learned from;
Flask Value error view function did not return a response

How do I upload images with Flask and requests?

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 :)

Cloud9 "Unable to load http preview" Flask project

I'm following a mooc for building quickly a website in flask.
I'm using Cloud9 but i'm unable to watch my preview on it, i get an :
"Unable to load http preview" :
the code is really simple, here the views.py code
from flask import Flask, render_template
app = Flask(__name__)
# Config options - Make sure you created a 'config.py' file.
app.config.from_object('config')
# To get one variable, tape app.config['MY_VARIABLE']
#app.route('/')
def index():
return "Hello world !"
if __name__ == "__main__":
app.run()
And the preview screen, is what I get when I execute
python views.py
Thank you in advance
you need to make FLASK_APP environment variable, and flask application is not running like python views.py but flask run. Quick start
# give an environment variable, give the absolute path or relative
# path to you flask app, in your case it is `views.py`
export FLASK_APP=views.py
#after this run flask application
flask run
I faced the same problem. There is no way we can preview http endpoints directly. Although in AWS documentation they have asked to follow certain steps, but those too wont work. Only way is to access it using instance public address and exposing required ports. Read here for this.

Categories

Resources