I created an endpoint in the flask file that looks like this
#app.route("/update", methods=['POST', 'GET'])
def update_func():
results = {
"method": request.method
}
return json.dumps(results)
I tried calling this function using both Postman and python, both are saying Flask is processing it as a get request.
import requests
r = requests.post("http://site.fakeurl.org/update", json={})
print r.json()
Is there a config file I need to change for this process as a POST request?
Is this happening to anyone else?
Did you try using http://www.site.faekurl.org/update ?
Some servers redirect http:// to http://www.-- and as a result, the POST request + it's data gets lost in the process.
Related
I'm trying to send an xlsx file using Python requests library. My request looks like this:
import requests
url_attachment = "http://127.0.0.1:5000/api/attachment"
payload={}
files=[('file',(filename, open(filename,'rb'),'application/octet-stream'))
]
headers = {}
requests.request("POST", url_attachment, headers=headers, data=payload, files=files)
and my mock server looks like this:
import flask
from flask import request
app = flask.Flask(__name__)
app.config["DEBUG"] = True
#app.route('/', methods=['GET'])
def home():
return "<h1>Hello World</h1>"
#app.route('/api/attachment', methods=['POST'])
def get_file():
data = request.files['file']
data.save('the-file.xlsx')
return "ok"
app.run()
The mock server works fine, and the file gets sent correctly.
However, when I call the actual API (that I have no access to), the file gets corrupted. The person who owns the API sent me the corrupted file, and after inspection I can see that the content got wrapped in this:
-------------------------------28947758029299
Content-Disposition: form-data; name="the-file.xlsx"; filename="the-file.xlsx"
Content-Type: application/octet-stream
//content
-------------------------------28947758029299--
Does someone have an idea why this is happening? What can I change in my function to stop this from happening? I have also tried changing the Content-Type to application/vnd.openxmlformatsofficedocument.spreadsheetml.sheet but apparently this results in the same problem.
This has been resolved now. If anyone comes across a similar issue in the future, the cause was the receiving method in the API considering content as 'multi-part form data'.
I have several Python scripts that are used from the CLI. Now I have been asked if I could provide a web API to perform some of the work normally done from the CLI. I would like to respond with JSON formatted data. I know little about JSON or API's.
How do I retrieve the query data from the http request?
How to a create the HTTP headers for the response from my script?
Given the following URL, how can I respond with a JSON reply of the name "Steve"?
http://myserver.com/api.py?query=who
I already have a functioning Apache web server running, and can serve up HTML and CGI scripts. It's simply coding the Python script that I need some help with. I would prefer not to use a framework, like Flask.
A simple code example would be appreciated.
The following is the Python code that I've come up with, but I know it's not the correct way to do this, and it doesn't use JSON:
#!/usr/local/bin/python3.7
import cgi # CGI module
# Set page headers and start page
print("Content-type: text/plain")
print("X-Content-Type-Options: nosniff\x0d\x0a\x0d\x0a")
# Form defaults
query_arg = None
# Get form values, if any
form = cgi.FieldStorage()
# Get the rest of the values if the form was submitted
if "query" in form.keys():
query_arg = form["query"].value
if query_arg == "who":
print("Steve", end="", flush=True)
You are trying to build a request handler with core python code. which is able to handle http request, In my opinion its not good idea as there are multiple securty scenarios attached with it, also in cross server request its bit difficult to handle all request and request scenarios . I will suggest to use Flask which is very lightweight and this will give an pre-setup of routing mechanism to handle all kind of request in very less code below is the snippet to generate http json response hope it helps
import sys
import flask
import random, string
from flask import jsonify
class Utils:
def make_response(self):
response = jsonify({
'message': 'success',
})
response.status_code = 200
return response
I'm trying to create a flask service in which I want to send the data coming from one request.form to another url in json format, Please can anyone help me to achieve this?
redirect(url_for('any_method'), json = json.dumps(my_form_dict))
When I try to execute the above code I'm getting following error:
TypeError: redirect() got an unexpected keyword argument 'json' The above is the error here.
You can redirect POST requests using 307 status code.
Use:
redirect(url_for('any_method', json=json.dumps(my_form_dict)), code=307)
For more information refer to this answer:
Make a POST request while redirecting in flask
It is not possible to redirect POST requests.
More info is here.
Your problem is that you are passing too much arguments to the redirect function. It only expects three parameters, location, code, and Response. If you want to pass extra parameters, use the Flask url_for method:
redirect(url_for('any_method', json=form_json))
Note the difference, you were passing the url_for and extra fields as two parameters. In my version, I've added the extra fields in the url_for, so redirect only receives one parameter.
I used the requests package to redirect a GET request to the POST one.
The trick is using flask.make_response() to make a new Resposne object.
In my scenario, the last response is an HTML text, so I get text as a response.
from flask import request, make_response
import requests
#app.route('/login', methods=['GET'])
def login():
data = {"data": request.args['data']}
redirect_response = requests.post('https://my-api/login', json=data).text
return make_response(redirect_response, 302)
I need a simple Client side that can send a bool valu if he is Alive, in a HTTP POST request. I have a Linux server running Apache.
I realized from Atermi(user who helped me), i new to use a requests library, something like this:
import requests
r = requests.post("http://127.0.0.1/post", data={'key': 'val'})
print(r.text)
But I don't know how to make my apache server receive the post requests.
In addition,when running the script I am receiving an error,
The requested URL '/' was not found on this servers.
I tried a server side, for testing in the same linux server and this is the
Code,
from flask import Flask, request
app = Flask(__name__)
#app.route('/', methods=['POST'])
def res():
print(request.form['key'])
return "Revived"
but recveing the following error:
runtimerror: working outside of the request context
Thanks!
I want to use flask to return JSON to the brower with or without simplejson (with appropriate headers) here is what I have so far for my flask application:
#app.route('/')
def hello_world():
QUERY_URL="http://someappserver:9902/myjsonservlet"
result = simplejson.load(urllib.urlopen(QUERY_URL))
return result;
Assuming the JSON output returned is:
{"myapplication":{"system_memory":21026160640.0,"percent_memory":0.34,
"total_queue_memory":4744,"consumers":1,"messages_unacknowledged":0,
"total_messages":0,"connections":1}
When I visit the page http://localhost:5000 however, I get a Internal Server Error. What must I do with "result" to get it to display appropriately? Or is there some way I can tell it to return with json headers?
When I add a print statement to print the result I can see the JSON, but in the browser it gives me an Internal Server Error.
import requests
r = requests.get(QUERY_URL)
return r.json
#normal return
return jsonify(username=g.user.username,
email=g.user.email,
id=g.user.id)
jsonify is available in flask. Here is the docs