I want to pass images through POST method in POSTMAN but I get None type response in the line request.files['image']
I have tried a number of different things but I am not able to solve the problem.
from flask import Flask,jsonify
from flask import request
import face_recognition
import json
app = Flask(__name__)
#app.route('/')
def index():
return ''
#app.route('/valid_faces', methods=['POST'])
def POST():
if request.method == 'POST':
# getting the images url from the request
print('....')
name1 = request.files['file'] if request.files.get('file') else None
print('....')
print (name1) # name2 = request.form.get('name2')
# map the url to the ones in the folder images
firstImage = name1
# loading the image inside a variable
firstImage = face_recognition.load_image_file(firstImage)
result=face_recognition.face_locations(firstImage)
if result:
# x={'valid_faces':True}
# return jsonify(x)
return "True"
else:
# x={'valid_faces':False}
# return jsonify(x)
return "False"
if __name__ == "__main__":
app.run(debug=True)
If you wish to append a file to a postman call it needs to be added to the body.
Check form-data and select file instead of text. You can now select a file with the windows file explorer.
To obtain the given file use the request package.
file = request.files['file']
The index has to be the same string you specified within the postman body data.
In Postman, do the following:
Set the method to POST
Set the body type to form-data
Establish Key/Value pairs for input. Set the value for the Key to
"file"
Mouse over the Key field and choose Text or File from the drop-down
menu
Click Send to process the request
In my case Postman set empty first value for FileStorage object in request.files . You can check this using:
print(str(request.files))
And in case of empty index instead
file = request.files['file']
try to use
file = request.files['']
follow this process: https://i.stack.imgur.com/GGm4I.png
Set Method to POST
Change body tab to form-data
Set key
in Value, hover, you can see file/text. in here select file
Select file you want to upload.
Send request.
you can do it
files = request.files.getlist("file")
Related
Question
I have created a dynamic route as /update/<randomString> in my Flask app.py file, where randomString is a randomly generated string with the length of 50. However if I search for /update/1 I am able to view the same dynamic route /update/<randomString> without any error! Can anyone explain why is it so?
See what I've tried so far:
#app.route('/')
def index():
randomString = ''.join(secrets.choice(string.ascii_uppercase+string.digits+string.ascii_lowercase) for k in range (50))
session['randomString'] = str(randomString)
return render_template('index.html')
#app.route('/update/<randomString>')
def update(randomString):
if 'randomString' in session:
randomString = session['randomString']
return render_template('update.html')
else:
return 'error...'
Link of the dynamic page at update.html page, where random string is passed with the help of session(defined at index.html page).
Dynamic page
Edit: I am also able to view dynamic route when I click on the link defined above and my URL section shows that long randomString. Problem is: I can access the same route when I search for http://127.0.0.1:5000/update/1
Screenshot one
Screenshot two
While storing the random string, the key you use is randomString. So you are storing the random string in a dict like
session['randomString'] = '1234567890'
Then when you access the session in the /update route you are just checking if session has a key named randomString. You should also check if session['randomString'] == '1234567890' and render the page only if the random string in session is the same as you created in the / path. You can replace the if with
if 'randomString' in session and session['randomString'] == randomString :
I am trying to write a dynamic page in Python with Flask on my pythonanywhere.com free hosting. I have the following code, hoping I could write to the resp variable to make my pages.
#app.route('/xdcc-search/search.html')
def search_app():
try:
with open('templates/xdcc-search/search.html', 'r') as dynamic:
dynamic.read()
except:
pass
dynamic.replace("<file>","MY_FILENAME.tar")
resp = make_response(render_template(dynamic), 200)
no_cache(resp)
return resp
I get an error stating dynamic is referenced before assignment. Is there a way to edit the template after render_template(filename) retreives and assembles the page?
When you do this:
with open('templates/xdcc-search/search.html', 'r') as dynamic:
dynamic.read()
...you are reading in the contents of the file, but you are throwing them away -- read() is a function that reads the contents of the file and returns them.
Fixing your code so that it actually does what you are trying to do gives this:
#app.route('/xdcc-search/search.html')
def search_app():
try:
with open('templates/xdcc-search/search.html', 'r') as dynamic:
contents = dynamic.read()
except:
pass
contents.replace("<file>","MY_FILENAME.tar")
resp = make_response(render_template(contents), 200)
no_cache(resp)
return resp
...but that is still wrong; render_template takes as its parameter the name of the file that contains the template, not its contents. So what you need to do to get this working would be to replace that render_template with render_template_string.
#app.route('/xdcc-search/search.html')
def search_app():
try:
with open('templates/xdcc-search/search.html', 'r') as dynamic:
contents = dynamic.read()
except:
pass
contents.replace("<file>","MY_FILENAME.tar")
resp = make_response(render_template_string(contents), 200)
no_cache(resp)
return resp
But this is still not using Flask templates the way they are meant to be used. The point of templates is that they should contain things in curly brackets to specify what changes should be made. Replacing a static string inside one with an explicit call to replace bypasses that and does a more primitive version of the same thing.
What you really should be doing is changing your template so that instead of having <file> inside, it, it has {{ file }}, and then you can replace all of that messy view code with this:
#app.route('/xdcc-search/search.html')
def search_app():
resp = make_response(render_template("xdcc-search/search.html", file="MY_FILENAME.tar"), 200)
no_cache(resp)
return resp
Finally, I'm not sure that you need that no_cache, as view functions are not cached by default. Also, the default status code on a response is 200. So probably all you need is this:
#app.route('/xdcc-search/search.html')
def search_app():
return render_template("xdcc-search/search.html", file="MY_FILENAME.tar")
I have a function calculate_full_eva_web(input:dict) it receives input dictionary several function applied on this input to create calculations dict, after calculations i want to send this data to html dashboard and after send data to html file i can play there with jinja stuff. i am unable to do so, i tried several ways but flask throws error. and also i don't know much about ajax ,may be ajax will do my work, let me know. that is why i am tagging ajax people on this post. Traceback is also attached..Thank you
In simple words, i want to send data to html in flask ! Please check my code. Let me know if i am doing anything wrong.
imports ...
from other file import other_functions
from other file import other_functions_2
from other file import other_functions_3
app = Flask(__name__, template_folder='templates/')
#app.route("/dashboard")
def calculate_full_eva_web(input:dict):
calculate_gap = other_functions(input)
calculate_matrix = other_functions_2(input)
average = other_functions_3(input)
data = dict{'calculate_gap':calculate_gap, 'calculate_matrix':calculate_matrix,'average':average}
return render_template('pages/dashboard.html', data = data)
if __name__ == "__main__":
app.run(debug=True)
The route receive a dict as input so you must change #app.route("/dashboard") to #app.route("/dashboard/<input>") and pass input to the route in the link of the route.
For example, I have a route as below.
#app.route('/user/<name>')
def user(name):
return render_template('home.html', name=name)
To pass name to the route, I access the link http://localhost:5000/user/myname.
I have tried to solve this problem for a week now and couldn't find a suitable solution.
I have a search bar to input gene ids (alternatively upload afile). It then queries the database and returns interactions between these genes. We display those interactions in a matrix on the html page. (I basically return a python array).
Now I want to include an export button to download the matrix / table in a csv or text file so the user can manipulate it for further research.
How can I do this without saving every query result in a file?
Because after returning the matrix, the python script (views.py) has run and the gene ids are gone.
Can it be done with jQuery?
Thank you so much for your help.
You only need to provide a link that contains current url plus a flag to indicate that it's a download csv request not a render page request:
def return_result(request):
# your original query
query = request.GET.get('id', None)
if query:
results = Model.objects.filter(field=query)
response = request.GET.get('download', None)
if response == 'csv':
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'
# create a csv
return response
else:
context = {'results': results}
return render(request, 'results.html', context)
In your page you create a link to download csv, {{ request.get_full_path }} is to get current url from request:
Download as CSV
I am trying to implement a function in Django to upload an image from a client (an iPhone app) to an Amazon S3 server. The iPhone app sends a HttpRequest (method PUT) with the content of the image in the HTTPBody. For instance, the client PUTs the image to the following URL: http://127.0.0.1:8000/uploadimage/sampleImage.png/
My function in Django looks like this to handle such a PUT request and save the file to S3:
def store_in_s3(filename, content):
conn = S3Connection(settings.ACCESS_KEY, settings.PASS_KEY) # gets access key and pass key from settings.py
bucket = conn.create_bucket("somepicturebucket")
k = Key(bucket)
k.key = filename
mime = mimetypes.guess_type(filename)[0]
k.set_metadata("Content-Type", mime)
k.set_contents_from_string(content)
k.set_acl("public-read")
def upload_raw_data(request, name):
if request.method == 'PUT':
store_in_s3(name,request.raw_post_data)
return HttpResponse('Upload of raw data to S3 successful')
else:
return HttpResponse('Upload not successful')
My problem is how to tell my function the name of the image. In my urls.py I have the following but it won't work:
url(r'^uploadrawdata/(\d+)/', upload_raw_data ),
Now as far as I'm aware, d+ stands for digits, so it's obviously of no use here when I pass the name of a file. However, I was wondering if this is the correct way in the first place. I read this post here and it suggests the following line of code which I don't understand at all:
file_name = path.split("/")[-1:][0]
Also, I have no clue what the rest of the code is all about. I'm a bit new to all of this, so any suggestions of how to simply upload an image would be very welcome. Thanks!
This question is not really about uploading, and the linked answer is irrelevant. If you want to accept a string rather than digits in the URL, in order to pass a filename, you can just use w instead of d in the regex.
Edit to clarify Sorry, didn't realise you were trying to pass a whole file+extension. You probably want this:
r'^uploadrawdata/(.+)/$'
so that it matches any character. You should probably read an introduction to regular expressions, though.