Reputation: 303
Hi when I try to run the code below I keep getting name 'headers' is not defined, I believe it has something to do with the indentation, I have tried indenting but it then affects the data variable described below
import requests
import psycopg2
conn_string = "host='xx' dbname='xx' user='xx' password='xx'"
conn = psycopg2.connect(conn_string)
cursor=conn.cursor()
def main():
headers = {
'authority': 'xx-api.xx.com',
'origin': 'https://www.example.com',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36',
'accept': '*/*',
'sec-fetch-site': 'same-site',
'sec-fetch-mode': 'cors',
'referer': 'https://example.com/xx-calendar',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8',
}
response = requests.get('https://example.com/en/api/v1/x/xxx', headers=headers)
data = response.json()['data']
fields = [
'dateUtc',
'countryCode',
'name',
'potency',
'previous',
'unit',
'volatility'
]
for item in data:
my_data = [item[field] for field in fields]
cursor.execute("INSERT INTO economic_calendar VALUES (%s, %s, %s,%s,%s,%s,%s,)", tuple(my_data))
if __name__ == '__main__':
main()
Upvotes: 0
Views: 106
Reputation: 42778
Everything belonging to main
must be indented the same level:
import requests
import psycopg2
conn_string = "host='xx' dbname='xx' user='xx' password='xx'"
def main():
headers = {
'authority': 'xx-api.xx.com',
'origin': 'https://www.example.com',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36',
'accept': '*/*',
'sec-fetch-site': 'same-site',
'sec-fetch-mode': 'cors',
'referer': 'https://example.com/xx-calendar',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8',
}
response = requests.get('https://example.com/en/api/v1/x/xxx', headers=headers)
data = response.json()['data']
fields = [
'dateUtc',
'countryCode',
'name',
'potency',
'previous',
'unit',
'volatility'
]
conn = psycopg2.connect(conn_string)
cursor=conn.cursor()
for item in data:
my_data = [item[field] for field in fields]
cursor.execute("INSERT INTO economic_calendar VALUES (%s, %s, %s,%s,%s,%s,%s,)", tuple(my_data))
if __name__ == '__main__':
main()
Upvotes: 1