How to specify Accept headers from rest_framework.test.Client? - python

I'm trying to set up an API endpoint to reply with HTML or JSON depending on the incoming request's Accept headers. I've got it working, testing through curl:
> curl --no-proxy localhost -H "Accept: application/json" -X GET http://localhost:8000/feedback/
{"message":"feedback Hello, world!"}
> curl --no-proxy localhost -H "Accept: text/html" -X GET http://localhost:8000/feedback/
<html><body>
<h1>Root</h1>
<h2>feedback Hello, world!</h2>
</body></html>
I can't figure out how to use the APITestCase().self.client to specify what content should be accepted, though.
My view looks like
class Root(APIView):
renderer_classes = (TemplateHTMLRenderer,JSONRenderer)
template_name="feedback/root.html"
def get(self,request,format=None):
data={"message": "feedback Hello, world!"}
return Response(data)
and my test code looks like
class RootTests(APITestCase):
def test_can_get_json(self):
response = self.client.get('/feedback/',format='json',Accept='application/json')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.accepted_media_type,'application/json')
js=response.json()
self.assertIn('message', js)
self.assertEqual(js['message'],'feedback Hello, world!')
which dies on the test for response.accepted_media_type. What's the right way to do this? All I can find says that the format argument should be sufficient.

As was rightfully stated here, the docs don't seem to say much about how to add headers to the request using the test client. However, the extra parameter can be used for that but the trick is that you have to write it the exact way the http header looks. So you should do this:
self.client.get('/feedback/', HTTP_ACCEPT='application/json')

Related

Django DRF JWT authentication get token - JSON parse error - Expecting value

I have simple Django DRF application setup which I have implemented JWT authentication.
I used the Django REST framework JWT documentation
I am using curl to test the implementation.
I can successfully get a token using the following notation used in the documentation:
$ curl -X POST -d "username=admin&password=password123" http://localhost:8000/api-token-auth/
The token is returned in following format:
{"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InNpdHJ1Y3AiLCJleHAiOjE1MTE2NTEyMTQsInVzZXJfaWQiOjEsImVtYWlsIjoiY3VydGlzLnBva3JhbnRAZ21haWwuY29tIn0.F1TSkxe5tQVpddetUdOJDdAPP1XB9Bimb5U3c75oWd0"}
However, when I try using this other variation, I get an error:
$ curl -X POST -H "Content-Type: application/json" -d '{"username":"admin","password":"password123"}' http://localhost:8000/api-token-auth/
The error I get is:
{"detail":"JSON parse error - Expecting value: line 1 column 1 (char 0)"}
I also had the same error when trying to refresh or verify the token:
Refresh:
$ curl -X POST -H "Content-Type: application/json" -d '{"token":"<EXISTING_TOKEN>"}' http://localhost:8000/api-token-refresh/
Verify:
$ curl -X POST -H "Content-Type: application/json" -d '{"token":"<EXISTING_TOKEN>"}' http://localhost:8000/api-token-verify/
I was adding the token as follows:
curl -X POST -H "Content-Type: application/json" -d '{"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InNpdHJ1Y3AiLCJleHAiOjE1MTE2NDg5MjIsInVzZXJfaWQiOjEsImVtYWlsIjoiY3VydGlzLnBva3JhbnRAZ21haWwuY29tIn0.T5h_PSvzvKOZCPTS60x5IUm3DgAsRCRmbMJeGWZk3Tw"}' http://localhost:8800/api-token-refresh/
Am I perhaps adding the token incorrectly? Does it need some other formatting with quotes?
Those requests are sending data in two different ways. The first request sends it as form data (x-www-form-urlencoded) which is what your endpoint is expecting and the second request sends it as application/json.
I'm not sure that the library you're using will handle a json request out of the box so one option would be to create a custom endpoint and use something like the following:
import json
def ParseFormData(self, request):
payload = json.loads(request.body.decode('utf-8'))
// use django auth to authorize request and return token
You can read more about it in this answer here: https://stackoverflow.com/a/29514222/5443056
There's instructions for manually creating auth tokens in your library's documentation. Here's the code:
from rest_framework_jwt.settings import api_settings
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
payload = jwt_payload_handler(user)
token = jwt_encode_handler(payload)
i suggest use json.dumps({key:value})

Django JWT Auth, why one request works and the other not

I was trying Django JWT Auth and noticed that the URL responds well to one type of post but doesn't respond well to another, but i can figure out why.
Basically, if i use the cURL POST referred in the readme.md, everything goes accordingly to planned:
$ curl -X POST -H "Content-Type: application/json" -d '{"username":"admin","password":"abc123"}' http://localhost:8000/api-token-auth/
but if you i use another type of cURL POST with the same info, it doesn't work:
$ curl -d 'username=admin&password=abc123' http://localhost:8000/api-token-auth/
I know that the "Content-Type" is diferent, but shouldn't the request be accepted in the same manner, they are both well formed posts?
Curl's -d option actually sends the request like it's a web browser. My guess is that the URL you're testing against doesn't have a standard web form, so it can't actually process the request.
TL;DR Pretty sure Django JWT Auth doesn't support the application/x-www-form-urlencoded content type.
From curl manual:
-d --data
(HTTP) Sends the specified data in a POST request to the HTTP
server, in the same way that a browser does when a user has
filled in an HTML form and presses the submit button. This will
cause curl to pass the data to the server using the content-type
application/x-www-form-urlencoded. Compare to -F, --form.
Hope this helps!

An example of POST request in Flask API gives "Method Not Allowed"

I'm using FLASK API and I want to use POST requests.
I want just to do an example with POST requests that will return something, I keep getting an error message "Method Not Allowed".
I want to give a parameter(e.g query_params = 'name1' ) to search for a user and to return a JSON, actually I don't know where to give this parameter and I don't understand why I'm getting that message.
Here I did a simple route:
#mod_api.route('/show-user', methods=['POST'])
def show_user():
query_params = 'name1'
query = {query_params: 'Myname' }
json_resp = mongo.db.coordinates.find(query)
return Response(response=json_util.dumps(json_resp), status=200, mimetype='application/json')
Any help please?
The likely reason is that you are probably not doing a POST request against the route, which only accepts POST requests. Here is a simplified example with the mongodb details removed to illustrate this.
from flask import Flask
app = Flask(__name__)
#app.route('/show-user', methods=('POST',))
def show_user():
return "name info"
if __name__ == "__main__":
app.run(debug=True)
Now if we do a POST request it works, but if we do A GET request it raises the error you saw:
curl -H "Content-Type: application/json" -X POST -d '{}' http://127.0.0.1:5000/show-user
name info
curl -H "Content-Type: application/json" -X GET http://127.0.0.1:5000/show-user
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>405 Method Not Allowed</title>
<h1>Method Not Allowed</h1>
<p>The method is not allowed for the requested URL.</p>

Body in Request ignored when forming POST dict in Django

I am working on a Django server that takes an integer from POST data. If I send the integer via GET there's no problems, but it gets dropped when sent via POST.
I run the server with:
./manage.py runserver 0.0.0.0:8000
and then generate the POST request with:
curl -X POST -H "Content-Type: application/json" -d '{"myInt":4}' "http://0.0.0.0:8000/myURL/"
I am using PDB in the view, and here is the result I am getting for the following commands:
request.method
> 'POST'
request.body
> '{"myInt":4}'
request.POST
> <QueryDict: {}>
I have used #csrf_exempt as a decorator for the view, just to make sure that isn't causing any problems.
Currently it is baffling me that request.POST does not contain myInt, is my POST request not well-formed?
Your post request is sending JSON not application/x-www-form-urlencoded
If you look at the django docs about HttpRequest.POST .
A dictionary-like object containing all given HTTP POST parameters, providing that the request contains form data. See the QueryDict documentation below. If you need to access raw or non-form data posted in the request, access this through the HttpRequest.body attribute instead.
You need to POST form encoded data. I didn't test this and haven't used curl in a while, but I believe the following should work.
curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "myInt=4" "http://0.0.0.0:8000/myURL/"

POST method to update XML file

I'm trying to use the following code to update a particular tag (<a>) text on file.xml
#app.route('/model', methods = ['POST'])
def api_post():
if request.headers['Content-Type'] == 'text/xml':
f = open("/home/file.xml", "w")
f.write(request.data)
f.close()
but the test with curl is not working...
curl -H "Content-type: text/xml" -X POST http://192.168.1.12:8080/model -d "<a>hello</a>"
Could someone help since I can't find any examples of flask and XML for the POST method?
Possibilities:
You're routing /data POSTs to api_post(), but you're sending
your curl test to /model.
HTTP header names are case-insensitive, but Python dictionary keys
are not. You're posting 'Content-type' but checking 'Content-Type'.
Suggestion: Expand upon "not working..." by providing any error messages or log entries which do not make sense to you. If there are no traces of trouble, add diagnostics until there are.

Categories