How do I loop over a WTForms all filled with in a class
What I have tested is just using the loop around it
Forms classes
class someForm(FlaskForm):
some_filled_one = StringField('some_filled_one')
some_filled_two = StringField('some_filled_two')
...
then I have a anther place were I want to loop over this fields.
dict = {"some_filled_one" : "some text", "some_filled_two" : "some text 2"}
form = someForm()
for key in dict.keys():
response = request.form[key]
... #do some thing
this givs me an error :
werkzeug.exceptions.BadRequestKeyError
werkzeug.exceptions.HTTPException.wrap.<locals>.newcls: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
Sorry, I don't have enough reputation to comment on this, so I have do draw an answer.
First, why do you create a dictionary for looping through request.form? Everything is accessable with request.form.keys(). And without sending a request before, the object request won't exist. So, looping trough the form objects you could either use request.form.keys() combined with request.form[key] or request.form.items()
Secondly, my guess is that whatever happens after #do some thing might be wrong.
Regards, Thomas
Related
I have dug far and deep but no working solution yet, based on some things I read from a thread somewhere, it seems you have to prefix headers with HTTP_ e.g. HTTP_AUTHORIZATION ends up being the Authorization header, based on that my current attempt is:
class TestImpersonatation(LogonUserMixin, GraphQLTestCase):
:
def test_...(self):
response = self.query(''' ...mutation here... ''',
headers = {
"HTTP_AUTHORIZATION": f"JWT {self.token}",
"HTTP_SET_COOKIE": f"my-jwt-token={self.token}"
},
variables={ ...vars... }
)
but alas, every time I get to my breakpoint there is only ever one cookie set, a csrf token. I am stumped but still trying... next it to se if a Client() instance can be passed in to work some magic instead of relying on the one created inside.
I use software that only lets me fetch information on all users, while my project requires me to get only one specific user. I only need his ID and I'm going to find it out by his e-mail (because it's unique).
The program creates an user (via POST) and stores his data (like email) in variables, then reads a provided list of devices that will be assigned to said user. To do this, the program has to:
Fetch all users (why software author didn't allow to fetch a single user is beyond me)
Filter users so it finds my newly created user <- here's my issue
Fetch all devices...
Filter devices...
Finally create a permission relationship between found user and device IDs
This is what I came up with so far:
inputText = self.imeiInput.GetValue().splitlines() # reads input and creates a list
url = "https://example.com/api/users/"
userList = requests.get(url, auth=(login, password)).content
foundUser = re.findall(givenMail, str(userList)) # givenMail provided by function argument
print(userList)
print(foundUser) # prints only searched mail
for imei in inputText:
self.TrackerAssign(imei, foundUser) # do your stuff
But it only confirms that there indeed is my email in the userbase, there's no other info (like ID I'm interested in). Here's a sample userList output (except that originally it's all in one line):
b'[{
"id":1,
"attributes": {
...
},
"name":"username",
"login":"",
"email":"test#example.com",
"phone":"999999999",...
},
{
"id":2,
"attributes": {
...
},
"name":"username2",
"login":"",
"email":"test2#exmaple.com",
"phone":"888888888",...
},
...]'
Then there's also a question how to only read the desired ID. Sorry if this is confusing, I barely know what I'm doing myself.
From your example it seems like you get a JSON response from the endpoint. This is great, because this JSON can be parsed to a list/dictionary!
Your approach can look something like this. In broad terms, this is a possible strategy:
Get all users from the users endpoint.
Parse the response JSON to a list of dictionaries.
Loop over all users, breaking the loop when you find your user.
Do something with the ID of the user that you found in your search.
response = requests.get(url, auth=(login, password)) # receive a Response instance
user_list = response.json() # parse the body to a dictionary
for user in user_list:
# Compare the email of this user with the target, using get to catch users with no email specified.
if user.get("email") == given_mail:
desired_user = user
break # if we find the correct user, we exit the loop
else:
# If we never find the desired user, we raise an exception.
raise ValueError("There is no user with email %s", given_email")
print(f"The ID of the user I am looking for is {desired_user["id"]}.")
I'm trying to read facebook conversations of a page using a python script. With this code
import facebook
at = "page access token"
pid = "page id"
api = facebook.GraphAPI( at )
p = api.get_object( 'me/conversations')
print p
I get a dictionary containing the following
{'paging': {'next': 'https://graph.facebook.com/v2.5/1745249635693902/conversations?access_token=<my_access_token>&limit=25&until=1454344040&__paging_token=<my_access_token>', 'previous': 'https://graph.facebook.com/v2.5/1745249635693902/conversations?access_token=<my_access_token>&limit=25&since=1454344040&__paging_token=<my_access_token>'}, 'data': [{'link': '/Python-1745249635693902/manager/messages/?mercurythreadid=user%3A100000386799941&threadid=mid.1454344039847%3A2e3ac25e0302042916&folder=inbox', 'id': 't_mid.1454344039847:2e3ac25e0302042916', 'updated_time': '2016-02-01T16:27:20+0000'}]}
What are those fields? How can I get the text of the message?
Edit: I tried asking for the "messages" field by adding
msg = api.get_object( p['data'][0]['id']+'/messages')
print msg
but it just returns the same fields. I've searched in the API docs for a while, but I didn't find anything helpful. Is it even possible to read the message content of a facebook page's conversation using python?
I managed to find the answer myself; the question was not well posed and did not match what I was exactly looking for.
I wanted to get the content of the messages of facebook conversations of a page. Following the facebook graph API documentation, this can be achieved by asking for the conversations ({page-id}/conversations), then the messages in said conversations ({conversation-id}/messages, https://developers.facebook.com/docs/graph-api/reference/v2.5/conversation/messages), and finally asking for the message itself should return a dict with all the fields, content included (/{message-id}, https://developers.facebook.com/docs/graph-api/reference/v2.5/message).
At least this is how I believed it should have been; however the last request returned only the fields 'created_time' and 'id'.
What I was really trying to ask was a way to fetch the 'message' (content) field. I was assuming the function graph.get_object() from the official python facebook sdk should have returned all the fields in any case, since it has only one documented argument (http://facebook-sdk.readthedocs.org/en/latest/api.html) - the graph path for the requested object, and adding additional field request is not allowed.
The answer I was looking for was in this other question, Request fields in Python Facebook SDK.
Apparently, it's possible to ask for specific fields ( that are not returned otherwise ) by passing an **args dict with such fields along with the path requested.
In a GET request to the Facebook graph that would be the equivalent of adding
?fields=<requested fieds>
to the object path.
This is the working code:
#!/usr/bin/env python
import facebook
at = <my access token>
pid = <my page id>
api = facebook.GraphAPI( at )
args = {'fields' : 'message'} #requested fields
conv = api.get_object( 'me/conversations')
msg = api.get_object( conv['data'][0]['id']+'/messages')
for el in msg['data']:
content = api.get_object( el['id'], **args) #adding the field request
print content
I'm writing an app to post json to Django, but get a 500 error in terminal like
[27/Jan/2015 20:50:38] "POST /datasave/ds/ HTTP/1.1" 500 10414
This is my jQuery code:
$(function() {
$('#upload').click(function() {
var json_obj = {
username: $('#username').val(),
password: $('#password').val(),
game_id1: '123',
csrfmiddlewaretoken: '{{ csrf_token}}'
};
$.post("http://192.168.0.109:8000/datasave/ds/", JSON.stringify(json_obj),
function(data) {
alert("OK");
},
"json");
})
})
And Django views code:
#csrf_exempt
def ds(request):
dicty = {}
if request.is_ajax:
if request.method == 'POST':
req = json.loads(request.body.decode("utf-8"))
obj, created =
Gamer.objects.update_or_create(
username=req.get(u'username', None),
password=req.get(u'password', None),
game_id1=req.get(u'game_id1', None))
print obj, created
dicty['username'] = req.get(u'username', None)
dicty['password'] = req.get(u'password', None)
dicty['create_at'] = str(timezone.now())
return JsonResponse(dicty)
As you are getting a 500 Internal server error one could assume that there is an issue in your view handler code. It's hard to say what's causing it really, so you should try to figure why it's happening. From looking at your code I can see two things that might cause this error.
First you are using dict as a variable name, which is probably a bad idea since dict is a built-in type in python.
The other possible cause could be the way your are accessing the req dict. You are accessing the keys username, password and game_id1. If any of these should be missing in the dict it will throw a KeyError exception. I like to access dicts using req.get('username', None) instead (replace None with another default value if you prefer. Another way to tackle that issue would be try/catch exception handling.
Also, depending on your Gamer model, trying to create a using an existing username (assuming you have unique=True) would probably throw an exception as well, so you should handle that as well (I think get_or_create could be handy here).
Generally when dealing with problems of this kind, use the inspector in your browser. It lets you see all the data sent and received during the request, which means (if you're running django in DEBUG mode) you'll also get to see the default stack trace page in the inspector. It should hold some valuable indication to what's causing the issue. Another option would be to write a small middleware or enable extended error logging to log errors to strout/stderr.
I have a simple form using a POST method, consisting of a text box and a file. After hitting submit, I can see the post in Firebug as follows:
Parts multipart/form-data
posttext Some text
image BlahJFIFBlahExifBlahPhotoshopBlahBinaryStuff etc...
The Tornado handler that receives it looks like:
class NewPostHandler(BaseHandler, MessageMixin):
#tornado.web.authenticated
def post(self):
message = {
'posttext':self.get_argument('posttext'),
'image':self.get_argument('image'),
etc
But Tornado's handler returns:
[W 100618 23:07:32 web:775] 404 POST /a/message/new (127.0.0.1): Missing argument image
I'm not quite sure what I'm doing wrong here. Am I correct in thinking 'argument' means a input element's 'name' attribute? How can I make the handler see the argument?
Thanks for your help, I've been struggling with this for an hour and must admit I'm stumped!
For file uploads you should use self.request.files instead of self.get_argument().