简体   繁体   中英

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. 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. Since you don't have a username variable, you get the 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.

For older versions of requests , use data = json.dumps(login_data) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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