Flask appropriate response for POST without template? - python

So I have a method for creating new exercises in the database for a workout app. I'm using angular to handle the ajax.
#app.route('/create', methods=['POST'])
def create():
data = request.get_json(request.data)
ex = Exercise(data['exName'], data['exType'])
db.session.add(ex)
db.session.commit()
After successfully committing, what is the best response to send back? I don't really need a success message, just need to let client know that it was successfully created. Thanks!

I think you can send back HTTP 204 which is described by w3.org rfc2616:
10.2.5 204 No Content
The server has fulfilled the request but does not need to
return an entity-body, and might want to return updated
metainformation. The response MAY include new or updated
metainformation in the form of entity-headers, which if
present SHOULD be associated with the requested variant.
I think you could do this in the end of your function
return '', 204

I think you should send 201 status(look here) Not 204 because you've just created new entity. And if you are trying to build good RESTful API you need to send 201 with the object you've created before.
And later, at the angular side, you can do what you want. You'll let users know about created exercise there.

Related

How to display an image from an external API as part of a response in Django

I have an external API that returns images and it requires a private key in order to access it. The content type it returns is 'image/jpeg'.
I am creating an API with the Django Rest Framework that uses this API. I also have a model with some basic char entries, and I want to return both those model entries as well as the image in a response, with the goal of making AJAX calls to it in JS and displaying both the data and the image in HTML.
I'm not exactly sure if I need to use Django forms? or if I can just make a call to the API in a plain js file hosted in my project? the latter would be ideal if I am able to send the image as part of the response... but ofcourse I don't want to expose the API key, which is part of the URL I am making a request to to get the image. I just want to essentially download the image and send it as a response.
This is the current code I have been testing out:
#api_view(['GET'])
def random_image(request):
response = requests.get('api url with secret key')
if request.method == 'GET':
return HttpResponse(response, content_type="image/jpeg")
I'm able to get an image response and see it when I make a GET request to the url in postman, however in Chrome I get a 500 server error.
Simply change
HttpResponse(response, ...)
To
HttpResponse(response.content, ...)
Should solve your issue my friend

Redirect to a different URL only changing the domain name in flask

I am using Python flask. I have a POST request with some payload coming on say:
abc.com/hello/hello1
I want to redirect this (302) to:
xyz.com/hello/hello1
only changing the domain name while keeping the remaining part as it is and also the payload. Is there a simple way to do this?
As per RFC, redirect requests (all 3xx) cannot contain request data or headers. You will miss the payload, supplied via POST in original request.
There are two possible workaround I could think of right away:
Give the client new URL, and implement further logic on client side;
Create a proxy handler on backend, which will do a request by itself and give the answer back as it's own.
EDIT: As per Andrejs Cainikovs's comment below, this would not work for a POST with payload.
In your endpoint, get the url that was used using request.url (see request API here for more options). Then you can rewrite it and make a redirect.
newUrl = "xyz.com/" + route
return redirect(newUrl, code=302)

Flask JWT extend validity of token on each request

Scenario
A logged in user will have a token expiry of 24 hours. Within that period, all request with #jwt_required decorator will have the current access token's expiry extended by another 24 hours. There is a maximum validity of 168(24 * 7) hours.
It is possible to use access_token and refresh_token.
ret = {
'access_token': create_access_token(identity=username, fresh=True),
'refresh_token': create_refresh_token(identity=username)
}
But that means every API call from my applicatino will be two requests:
1. Actual HTTP Request
2. Refresh the auth token
#app.route('/refresh', methods=['POST'])
#jwt_refresh_token_required
def refresh():
current_user = get_jwt_identity()
ret = {
'access_token': create_access_token(identity=current_user)
}
return jsonify(ret), 200
Is there a way to implicitly extend an auth token?
EDIT: There is now documentation around this here: https://flask-jwt-extended.readthedocs.io/en/latest/refreshing_tokens/
Author of flask-jwt-extended here. Technically you cannot actually extend a token, you can only replace it with a new JWT that has a new expires time. There are a few ways you could simulate this though.
First, instead of having the client request a new token, you could have the server itself just implicitly send back a new token on every request. You could send the new JWTs back in a header instead of in the JSON payload, so that you wouldn't have to modify you JSON data to account for the possibility of a new JWT. Your clients would need to be aware of this though, they would need to check for that new header on every request and replace their current JWT with the new one if it is present. You could probably use a flask after_request method to do this, so you didn't have to add that functionality to all your endpoints. A similar effect could be achieved when storing the JWTs in cookies, with the differences being that cookies are automatically stored in your browser (so your client wouldn't have to manually look for them on every request), and with the added complexity of CSRF protection if you go this route (http://flask-jwt-extended.readthedocs.io/en/latest/tokens_in_cookies.html).
The above should work fine, but you will be creating a lot of access tokens that are thrown away right after being created, which probably isn't ideal. A variation of the above is to check if the token is near expiring (maybe if it is more then half way to being expired) and only create and return a new token if that is the case. Another variation of this would be to have the client check if the token is about to expire (via javascript) and if it is, use the refresh token to request a new access token. To do that, you would need to split the JWT on dots ('.'), base64 decode the second set of strings from that split (index 1), and grab the 'exp' data from there.
A second way you could do this is actually wait for a token to expire, and then use the refresh token to generate a new access token and remake the request (reactive instead of proactive). That might look like making a request, checking if the http code is 401, if so use the refresh token to generate a new access token, then making the request again.
Hope this helps :)
app = Flask(__name__)
app.config["JWT_SECRET_KEY"] = "super-secret" # Change this!
app.config["JWT_ACCESS_TOKEN_EXPIRES"] = timedelta(hours=1)
app.config["JWT_REFRESH_TOKEN_EXPIRES"] = timedelta(days=30)
jwt = JWTManager(app)
change time according to your requirement

Send HTTP response that doesn't change the user's current page

I have a JavaScript bookmarklet that POSTs information to a (Flask powered) server while the user is on some other page (i.e. not one on my server). I don't want to interrupt the user's browsing by hijacking their session with my server response.
My initial thought was that I could suppress the HTTP response from Flask somehow; prevent it from sending anything to the client so they aren't mysteriously redirected. I was hoping I could do this by perhaps having a null return from a view.
I then thought that might be some HTTP response that lets the client know the information was successfully submitted, but will leave the client on their current page. Suppose a header value like "Here is the result of your request, but you should not alter your current display"?
To answer your amended question, yes there is such a response. From RFC 2616-section 10 (emphasis added):
10.2.5 204 No Content
The server has fulfilled the request but does not need to return an
entity-body, and might want to return updated metainformation. The
response MAY include new or updated metainformation in the form of
entity-headers, which if present SHOULD be associated with the
requested variant.
If the client is a user agent, it SHOULD NOT change its document view
from that which caused the request to be sent. This response is
primarily intended to allow input for actions to take place without
causing a change to the user agent's active document view, although
any new or updated metainformation SHOULD be applied to the document
currently in the user agent's active view.
The 204 response MUST NOT include a message-body, and thus is always
terminated by the first empty line after the header fields.
Thus from flask you can do something like this. Remember, the response must not include a message body, so any data you want to send back should be put into a cookie.
#app.route('/')
def index():
r = flask.Response()
r.set_cookie("My important cookie", value=some_cool_value)
return r, 204
No, it is not possible. Flask is built on Werkzeug, which implements the WSGI spec. The WSGI cycle requires sending a response to each request. Droping the response would require control over the TCP/IP connection at a far lower level even that HTTP. This is outside the domain of WSGI, therefore outside the domain of Flask.
You could return an error code, or an empty body, but you have to return something.
return '' # empty body

python how to handle http request and response

I have two questions. I am new to python and not fluent enough with all the BIF's in python.
I am developing a website database is on amazon simple db.
I am handling all database related queries and code using python scripts.
My first question is given an HTML page where the user gives his his login credentials I call in a python script using my handler javascript function send in a post request and get a response from my python script.
I can send a post request all right and get the values from sdb for validation. What I need to know is how to send in a response from my script back to my html page which could react to the information given.
My second question is how do I maintain an HTTP session using python?
My python code is given below although it shouldn't make for much since no response code is added:
form=cgi.FieldStorage()
organisationID= form['orgID'].value
username= form['username'].value
password= form['password'].value
sdb=sdbhelper.connect()
connection= sdb.get_domain('AdminTable')
itemnames=''
flag=False
for item in connection:
if (item.name==username+'$'+organisationID):
retrieved_item=connection.get_item(item.name)
if(retrieved_item['Password']==password):
flag=True
#Now Id like to respond with flag so that login validation can be done
If I am correctly getting your question what you want to do is to create a small API , Where you send some information to a webpage and get some other .
What you can do is once the user is authenticated you should return it a access key that is valid for a short time period .
One of the way to send data could be inform of JSON objects .
For example if user is authenticated then return
{
'KEY' : 'dklsfeir5rufui435uejhfjh5ewh5rf'
}
From the next request you can associate this short lived key along the url for access .For example send the next request to abc.py?key=dklsfeir5rufui435uejhfjh5ewh5rf (by get or by post ) . If the key is valid then process the request else send a json response saying error occurred .
The main advantage of using JSON is it can be easily decoded/ encoded for communication
(JSON | http://docs.python.org/2/library/json.html )
Secondly as you have generated access key you would not require any session .

Categories

Resources