Flask request csv [duplicate] - python

This question already has answers here:
Get the data received in a Flask request
(23 answers)
Closed 3 years ago.
I have a csv file, which I need to post on my server, convert it to json and send it back. With JSON, you can simply do request.json(Force=True), however I am not sure how to make flask to read my csv.
So far I have this:
#application.route('/postcsv', methods=['POST'])
def csv_view():
content = request.files(force=True)
stream = io.StringIO(content.stream.read().decode("UTF-8"), newline = None)
csv_input = csv.reader(stream)
print(csv_input)
return csv_input
if __name__ == '__main__':
application.run(debug=True, host='0.0.0.0')
The error I am getting is TypeError: 'ImmutableMultiDict' object is not callable. I think my approach overall is wrong but I am not sure

You got this error because request.files is not a function and thus can't be called.
Instead, you should use request.files[<KEY>]. See: Not able to parse a .csv file uploaded using Flask

Related

cURL an API in python and return the response as JSON [duplicate]

This question already has answers here:
HTTP requests and JSON parsing in Python [duplicate]
(8 answers)
Closed 4 months ago.
I'm learning Python and try to use it in my class project. I'm looking for a way to curl an API and return the response json. For example, the response after curling an API is JSON and how can I return it also as JSON
response = requests.get("https://github.com/timeline.json")
response = response.content
return response doesn't return it in json while return with jsonify(reponse) get this error (Object of type bytes is not JSON serializable).
Sorry for my English.
response = requests.get("https://github.com/timeline.json")
response_json = response.json()
print(response_json["message"])
print(response_json["documentation_url"])
The method json() returns the json-encoded content of a response as a dict. Additionally, you may want to use the new API at https://api.github.com/events (docs).

Flask Application - argument of type 'NoneType' is not iterable [duplicate]

This question already has answers here:
How to POST JSON data with Python Requests?
(10 answers)
Closed 3 years ago.
I've wrote a little flask application.
I send a request with json data (python script) to the flask server (ubuntu 18.04 with python 3.6.7),
and the server evaluate these data...
Client:
data = { 'serial': '12345'
'printerConfig': {
'virtualPrinter1': 'physicalPrinter1',
'virtualPrinter2': 'physicalPrinter2',
'virtualPrinter3': 'physicalPrinter3'
}
}
r = requests.get("http://127.0.0.1/webservice", json=data)
Server:
#app.route('/', methods=['GET', 'POST'])
def webservice():
if request.method == 'GET':
serial = request.json['serial'] if 'serial' in request.json else None
printerConfig = request.json['printerConfig'] if 'printerConfig' in request.json else None
I have tested this code in pyCharm with the development server and always works fine.
After that I have tried to implement that to an Apache2 server.
Now I get the following error message in apache-error.log.
ERROR:flask.app:Exception on / [GET]
Traceback (most recent call last):
...
File "/var/www/html/webservice/webservice.py", line xx, in webservice
serial = request.json['serial'] if 'serial' in request.json else None
TypeError: argument of type 'NoneType' is not iterable
Print of request.json shows only None.
Exactly the same code on the development server is running.
Instead of request.json I also tried request.data, with the same result.
Is there a specially setting for the Apache2?
Has anyone an idea?
Best regards
flo
You are making a get request.
Try making a post request to your webservice
r = requests.post("http://127.0.0.1/webservice", json=data)
You will never include the json="" when making a get... that is for only posting/updating json to the webserver
Remember, GET in http terms is only for requesting content from a URL endpoint. POST is to send new content to the URL endpoint.
GET/POST
Another quick point... Try just printing request.json on your back end/flask app before the serial = request.json['serial'] if 'serial' in request.json else None etc... just to make sure that the data is arriving correctly upon being posted.

Take data from html form and send back with flask [duplicate]

This question already has answers here:
Get the data received in a Flask request
(23 answers)
Converting Flask form data to JSON only gets first value
(2 answers)
Return JSON response from Flask view
(15 answers)
Closed 4 years ago.
I want to take data from html form with the python flask and send data back at the same html file. Can you help me with an example or some tips? Thank you.
You can use request.form, like the following:
from flask import Flask, request
app = Flask(__name__)
#app.route('/path_form_submits_to', methods=['POST'])
def my_handler():
return request.form.get("field_name", "default value if field isn't there")

Mailgun forwarding e-mail as POST data to Python Flask [duplicate]

This question already has answers here:
Get the data received in a Flask request
(23 answers)
Closed 5 years ago.
I can't figure this one out, it's not in the request.JSON and the request.data is coming up as empty bytes in the debug. There appears to be a post but the data is disappearing? Is this a bug with Flask?
Here's a link to their documentation page that has a Django example: https://documentation.mailgun.com/en/latest/quickstart-receiving.html#supported-actions-for-routes
Figured this out: Clue was in the header
'Content-Type': 'application/x-www-form-urlencoded'
Flask automatically strips out form data into request.form leaving request.data and request.json empty:
#app.route("/test-mail/", methods=["POST"], strict_slashes=False)
def test_mail():
print(request.form)
return 'OK'

How to use flask request properly to retrieve data from JSON?

I looked many questions similar to my title but I have not found any that had same problem as me yet.
I did requests.post to post JSON to API restful server. Below is the snippet
import requests
def upload_data():
url = "http://127.0.0.1:8088/"
data = {"value":"abc123"}
response = requests.post(url, data=data)
print response.status_code, response.reason, response.text
upload_data()
And for the server side
from flask_restful import Api, Resource
from flask import request
class MyAPI(Resource):
def get():
pass
def post(self):
value = request.data['value']
response_object = {
'value':value
}
return response_object, 201
I was hoping to get the POST function to work by showing the result of 201 Created with
{
'value':'abc123'
}
But whenever I run the script, it gives me error saying that
value = request.data["value"]
TypeError: string indices must be integers, not str
I am sorry if this is a bad question but if anyone could show me what I have been missing in this script, I really appreciate it. Thank you.
That's because request data hasn't been parsed into a python dictionary. Were you perhaps thinking of
data = json.loads(request.data)
However please note that you are not actually posting a JSON body to your flask server. You are posting multipart formdata. So you may probably be looking for the answer posted by luoluo.
One the other hand if you really wanted to deal with json, The correct way to send json looks something like this:
requests.post(url, json=data)
And then the loads as suggested.
The request.data is a string, while request.values is a MultiDict.
You need update your code to :
value = request.values.get('value')
instead of
value = request.data['value']
According to the doc
args
A MultiDict with the parsed contents of the query string. (The part in the URL after the question mark).
form
A MultiDict with the parsed form data from POST or PUT requests. Please keep in mind that file uploads will not end up here, but instead in the files attribute.
values
A CombinedMultiDict with the contents of both form and args.
data
Contains the incoming request data as string in case it came with a mimetype Flask does not handle.

Categories

Resources