简体   繁体   English

我不断收到“ NameError:名称'用户名'未定义”错误

[英]I keep receiving “NameError: name 'username' is not defined” error

I'm having immense trouble logging into an online account via python 2.7.11. 我在通过python 2.7.11登录到在线帐户时遇到了很大的麻烦。 I've spent many hours trying to figure it out, and going through my short code over and over again. 我花了很多时间试图找出答案,然后一遍又一遍地浏览我的短代码。 If anybody could please help me with this, I will be you humble servant. 如果有人可以帮助我,我将是你谦卑的仆人。

My code is: 我的代码是:

import requests

with requests.Session() as c:
    url = "https://www.matchbook.com/bpapi/rest/security/session/"
    login_data = {
        username: "Marcel",
        password: "*******"
    }
    c.post(url,data = login_data)
    page = c.get("https://www.matchbook.com/bpapi/rest/security/session/")
    print page.content

to which I get the error: 我得到的错误:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
NameError: name 'username' is not defined

I have also tried defining the username and password variables as variables and putting the username and password key's in inverted commas in the dictionary. 我还尝试过将用户名和密码变量定义为变量,并将用户名和密码键放在字典中的反逗号中。

To which I get the response: 我得到的答复是:

<Response [415]>
{"errors":[{"messages":["Please login to continue"]}]}

Any help, please! 任何帮助,请!

You probably meant: 您可能的意思是:

login_data = {
    "username": "Marcel",
    "password": "*******"
}

What you have is trying to look up a variable username and use it's value as the key. 您正在尝试查找变量username并将其值用作键。 Since you don't have a username variable, you get the NameError . 由于没有username变量,因此会得到NameError

In c.post(url,data = login_data) change data to json as the data needs to be JSON encoded and the way you've done it is form encoded. c.post(url,data = login_data)data更改为json因为数据需要进行JSON编码,并且您完成处理的方式是表单编码。

For older versions of requests , use data = json.dumps(login_data) . 对于旧版本的requests ,请使用data = json.dumps(login_data)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM