Django rest framework, serializer invalid when sent through Angular - python

I'm having a problem where when I make a post request from my Angular application served through Django I get invalid serializers, even if the output is correct.
I console log the sent data:
{"email":"example#gmail.com","username":"example","password":"plaintextforthisexample","confirm_password":"plaintextforthisexample"}
Which gives me the response Bad Request (which I have set to happen when serializer.is_valid() is false).
However, if I copy and paste what's in the console log into the browsable API under raw data it accepts it and creates a user.
I can successfully send get-requests to the same API and get the data back, and the permissions for getting and posts are the same, although that would result in another type of error.
The content type is correct as well, when not I get a 415. If the URL is wrong I get a 500. And I can see on the Django server log that post requests are coming in.
Could it be because I'm running it from an angular template and not a Django one?
EDIT:
Picture of the console:

Issue 1: The console logged output that worked in Django was not the one actually being sent, resulting in a JSONParse error.
It looked like something like this
function(formobject){
let payload = JSON.stringify(formobject)
console.log(payload)
return formobject
Issue 2: Now Django gives my my custom response on arrival:
Status:'Bad Request'
Message:'Data does not fullfill requirements for creating a user'
And does not allow me to copy-paste the JSON-output from the console into the API raw data-form.
Solved by not using the same password I had been using for about 15 tries. Seems Django detects common passwords, has not been fully tested.

Related

user email (correctly) shows as verified on frontend but not backend in modified firenotes

To address the close votes, all I'm asking for here is how to check that a user has verified their email in python on app engine.
The relevant bit of backend python code is:
id_token = request.headers['Authorization'].split(' ').pop()
claims = google.oauth2.id_token.verify_firebase_token(
id_token, HTTP_REQUEST, MY_PROJECT_ID)
if not claims:
return 'Unauthorized', 401
logging.warn('email verified? {}'.format(claims['email_verified'])) # always False
Original post:
I'm messing around with the firenotes example code. I've disabled everything but email log in, and want to make sure on the backend that the user has verified their email address. Inside frontend/main.js, checking user.emailVerified gives me the correct value.
However, this is not the case inside of backend/main.py.
Inside of list_notes() if I add a logging.warn(claims) I invariably see a key-value pair u'email_verified': False. I've tried restarting the server after verifying to avoid caching issues (which if they exist would still suck) but can't seem to actually detect whether the user has clicked the verification link in their email on the backend.
Is there something I need to add or configure to get the backend to be able to see (or maybe check for) email verification?
I just ran into exactly the same issue. The problem seems to be that the attributes associated with a particular firebase token become stale, and this problem only affects token-based verification on the back end. Solution: If the user signs out and back in after email verification, then the information is updated.
More precisely, here is the current behavior. In Javascript, on the front end, firebase.auth().currentUser.emailVerified is correctly true immediately after user verifies email and the page is refreshed. However, when the corresponding firebase token is sent to the server via user.getIdToken().then(function(token) { sendToServer(token); }), and then verified using Google App engine python library on the back end as uinfo = google.oauth2.id_token.verify_firebase_token(token, google.auth.transport.requests.Request()), then uinfo['email_verified'] remains False until user re-signs in and an updated token is issued.

No Logs in django developemnet server

i am trying to hit the django REST API using POSTMAN , i am able to save the data using django rest views, but when i am trying to save data using the POSTMAN the api is giving 500 , and also no logs are printed on console
it just print this
[09/Apr/2016 10:08:28]"POST /userprofile HTTP/1.1" 500 73961
the actual error is not clear why this happens, please help
Change the value of DEBUG variable in settings.py to True.
It give you all the informations you need in your browser if an error occurs (and in the console as well).

Python-Eve: formatting GET response to HTTP 200

I have Python-Eve running with MongoDB on a Ubuntu VM. I am trying to write an api to handle POST requests from an Iridium RockBLOCK modem. I have tested the API with Chrome Postman, and am able to successfully POST data.
When I try and send messages from my RockBLOCK I get 422 error messages on the VM. I am pretty sure this is because the RockBLOCK is not able to handle XML or JSON data, and is set up to simply look for an HTTP 200 response.
So how would I setup eve to respond with solely HTTP 200 when the POST request is received?
API Format taken from RockBLOCK Web Services Guide.
The 422 is returned from Eve when a validation error occurs. I would look into your request payload and make sure it adheres to validation rules. A typical example of a response like this would be when you have a unique rule for a field, and a POST comes in with an already used value for that field.
So how would I setup eve to respond with solely HTTP 200 when the POST request is received?
Right now you can disable either JSON or XML responses by respectively setting JSON = False or XML = False, but not both. Since Eve is a Flask application you could look into changing the response on the flight but again, given the error you are getting I don't think that is the problem you are facing right now.

How to create a Wikipedia bot to add a new section to a talk page?

We need to implement a bot which posts new sections on Wikipedia Talk pages.
As a matter of efficiency, we prefer to use python HTTP POST requests using MediaWiki API rather than available MediaWiki libraries.
We have not requested for an approval for the bot, and we are just trying to implement a trial version to test the bot on our own Talk pages.
For this purpose, I went through the following steps:
1- As discussed at https://en.wikipedia.org/wiki/Wikipedia:Creating_a_bot:
Create an account for your bot. Click here when logged in to create the account, linking it to yours. (If you do not create the bot account while logged in, it is likely to be blocked as a possible sockpuppet or unauthorised bot until you verify ownership)
Create a user page for your bot. Your bot's edits must not be made under your own account. Your bot will need its own account with its own username and password.
So, I logged in to my own Wikipedia account, and created a new account (for the bot).
2- As discussed at "API:Login" page: (Sorry, because of having less than 10 reputation, I am not able to add more than 2 links)
Logging in through the API requires two requests. For the first request, I wrote the following code in python:
def logInRequestToWikipedia():
# Add required parameters to the request.
request = { 'action' : 'login' }
request['lgname'] = 'BotName'
request['lgpassword'] = '*************'
url = 'https://en.wikipedia.org/w/api.php'
headers = { 'content-type' : 'application/x-www-form-urlencoded' }
r = requests.post(url, data = json.dumps(request), headers=headers)
The response starts with an error as follows:
<error code="help" info="" xml:space="preserve">
And continues with the API documentation.
3- As discussed at "API:Edit_-_Create%26Edit_pages" page:
Note: In this example, all parameters are passed in a GET request just for the sake of simplicity. However, action=edit requires POST requests; GET requests will cause an error. Do not forget to set the Content-Type header of your request to application/x-www-form-urlencoded. The token that you received is terminated with +\, this needs to be urlencoded (so it will end with %2B%5C) before it is passed back.
I added each of the following parameters separately and both together in the request data and tried all three cases, but it returns the same response.
request['lgtoken'] = '%2B%5C'
request['Content-Type'] = 'application/x-www-form-urlencoded'
4- Also I tried each of the followings in my request data, but it returns the same response:
request['format'] = 'json'
request['format'] = 'xml'
5- Moreover I found the following instruction at "User-Agent_policy" page:
User agents (browsers or scripts) that do not send a User-Agent header may now encounter an error message like this:
Scripts should use an informative User-Agent string with contact information, or they may be IP-blocked without notice.
User agents that send a User-Agent header that is blacklisted (for example, any User-Agent string that begins with "lwp", whether it is informative or not) may encounter a less helpful error message (lie) like this:
Our servers are currently experiencing a technical problem. This is probably temporary and should be fixed soon. Please try again in a few minutes.
This change is most likely to affect scripts (bots) accessing Wikimedia websites such as Wikipedia automatically, via api.php or otherwise, and command line programs.[3] If you run a bot, please send a User-Agent header identifying the bot and supplying some way of contacting you, e.g.:
User-Agent: MyCoolTool/1.1 (http://example.com/MyCoolTool/; MyCoolTool#example.com) BasedOnSuperLib/1.4
Do not copy a browser's user agent for your bot, as bot-like behavior with a browser's user agent will be assumed malicious.[4] For more information, please refer to the MediaWiki API Documentation
That's why I also tried my script with the following parameter, but the error response did not change:
request['User-Agent'] = "MyCoolTool/1.1 (http://example.com/MyCoolTool/; MyCoolTool#example.com) BasedOnSuperLib/1.4"
Do you think the problem can be related to the fact that we have not requested for an approval for the bot yet? Because we are just trying to implement a trial version to test the bot on our own Talk pages, and apply for the approval after making sure everything will work.
I'm pretty sure the problem is this line:
request['lgtoken'] = '%2B%5C'
The Login API you linked to doesn't include an lgtoken on the initial login attempt; it's only sent on the second ("Confirm token") step, using the token value from the NeedToken response.
And +\ doesn't look like a valid token.
So it's not surprising that you're getting an error.
Meanwhile, when I test this with my Wikipedia account, I get an error if I include that line, and success if I don't, which validates my suspicion that this is the problem.

How to redirect and then display errors with Google App Engine

I'm working on a Google App Engine project that collects stories submitted by users.
This is how I handle submission errors in the post method of my Request Handler:
# get the title and content using self.request.get()
errors = []
if not title:
errors.append("Please enter a title.")
if not content:
errors.append("Please enter a story.")
if not errors:
# create the story, save it to the database
# redirect to the story's page
else:
# pass the title and/or content to a template
# pass the error message(s) to a template
# the same template that displays the submission form is used here
The problem: since my form sends posts to example.com/createstory.do -- if there are errors I end up redisplaying the form page at that address.
What I want to happen: redirect the user back the page where they submitted the form: example.com/Share, while at the same time displaying the error messages and redisplaying the submitted form data.
What's the easiest way to do this?
I know I could just have /Share handle both get and post requests, but I'm looking for a solution that I can use even when doing that wouldn't be an option.
You could redirect to /Share including the errors in a GET variable in the URL, if you're absolutely sure you need to use separate URLs. Of course, this makes your URL ugly since it now has all of the error information in it.
Another option would be to redirect back to Share and have the errors stored in cookies or in a session variable.
Combining either of these with client-side form validation in Javascript before submitting in the first place so the ugly solution isn't hit in most cases might be the best option.
There's no 'clean' way of doing this, because you cannot redirect POST requests (and have the redirected request also make a POST). The standard - and cleanest - approach is to have the same URL display the form when fetched with GET, and accept the data when fetched with POST.

Categories

Resources