peewee always displays None, but the user is in the database - python

The screenshot shows that the user is in the database, but peewee thinks differently :c
user in database
console input
#bot.message_handler(func = lambda message: message.text in ['/start', '🏠 Главное меню 🏠'])
def start(message) -> None:
try:
check = users.get_or_none(users.user_id == message.from_user.id)
print(check)
if check == None:
logger.info('NEW user!')
short_id = random.randint(100000, 999999)
try:
refer_id = message.text.split()[1]
refer_id = int(refer_id)
except:
refer_id = 0
passw = generate_passw(len = 12)
users.create(user_id = message.from_user.id, short_id = short_id, passw = passw, plan = 'net', refer_id = refer_id, balance = 0.0)
bot.send_message(chat_id = message.from_user.id, text = welcome_new, parse_mode = 'Markdown', reply_markup = start_)
else:
bot.send_message(chat_id = message.from_user.id, text = welcome_back, parse_mode = 'Markdown', reply_markup = start_)
except:
logger.exception('uwuth')

Related

'timestamp' messages appeared on my terminal, but i didn't code print('timestamp')

enter image description hereI made my autobot for coin trade.
I'm using iterm2 terminal to operate my code.
But there's some problem I don't understand.
first I use the same fuction by changing parameter, symbolname etc.
but on the terminal window for A coin, there's only 'timestamp' message.
i can't tell if it is error or not because there's no error message
and i didn't code print('timestamp')
on the other terminal windows for other coin, there's no such a message.
I guess my explanation is not enough.
but if you have any idea about this kind of situations, please tell me.
I'm using python.
thank you already!!
sometimes, although i didn't change anytihng.
'timestamp' message was disappeared.
enter image description here
enter code here
def runBot(symbol, second=int):
try:
subtitle = 'B'
fourth_interval = '30m'
symbol = symbol
path = path
df_1 = callChart(exchange=exchange, symbol=symbol, interval='15m')
df_2 = callChart(exchange=exchange, symbol=symbol, interval='5m')
df_3 = callChart(exchange=exchange, symbol=symbol, interval='1m')
df_4 = callChart(exchange=exchange, symbol=symbol, interval='30m')
df_5 = callChart(exchange=exchange, symbol=symbol, interval='1h')
df_6 = callChart(exchange=exchange, symbol=symbol, interval='4h')
df_7 = callChart(exchange=exchange, symbol=symbol, interval='2h')
n4hma2 = df_6.ma20[-1]
n4hma6 = df_6.ma60[-1]
n4hma8 = df_6.ma80[-1]
p4h_rsi = df_6.rsi[-2]
p4h_open = df_6.open[-2]
p4h_close = df_6.close[-2]
n1hma2 = df_5.ma20[-1]
n1hma6 = df_5.ma60[-1]
n1hma8 = df_5.ma80[-1]
n1h_low = df_5.low[-1]
n1h_high = df_5.high[-1]
n1h_open = df_5.open[-1]
p1h_rsi = df_5.rsi[-2]
p1hma2 = df_5.ma20[-2]
p1hma6 = df_5.ma60[-2]
p1hma8 = df_5.ma80[-2]
p1h_close = df_5.close[-2]
n30ma2 = df_4.ma20[-1]
n30ma6 = df_4.ma60[-1]
n30ma8 = df_4.ma80[-1]
n30_high = df_4.high[-1]
n30_low = df_4.low[-1]
n30_open = df_4.open[-1]
p30_rsi = df_4.rsi[-2]
p30_rsi = df_4.rsi[-2]
p30_close = df_4.close[-2]
pp30_close = df_4.close[-3]
ppp30_close = df_4.close[-4]
p30ma2 = df_4.ma20[-2]
p30ma6 = df_4.ma60[-2]
p30ma8 = df_4.ma80[-2]
pp30ma2 = df_4.ma20[-4]
pp30ma6 = df_4.ma60[-4]
pp30ma8 = df_4.ma80[-4]
ppp30ma2 = df_4.ma20[-4]
ppp30ma6 = df_4.ma60[-4]
ppp30ma8 = df_4.ma80[-4]
p4_30ma2 = df_4.ma20[-5]
p4_30ma6 = df_4.ma60[-5]
p4_30ma8 = df_4.ma80[-5]
n_price = df_1.close[-1]
n15ma2 = df_1.ma20[-1]
n15ma6 = df_1.ma60[-1]
n15ma8 = df_1.ma80[-1]
p15_close = df_1.close[-2]
p15_open = df_1.open[-2]
n15_high = df_1.high[-1]
n15_low = df_1.low[-1]
p15ma2 = df_1.ma20[-2]
p15ma6 = df_1.ma60[-2]
p15ma8 = df_1.ma80[-2]
n5ma2 = df_2.ma20[-1]
n5ma6 = df_2.ma60[-1]
n5ma8 = df_2.ma80[-1]
n5_high = df_2.high[-1]
n5_low = df_2.low[-1]
p5ma2 = df_2.ma20[-2]
p5ma6 = df_2.ma60[-2]
p5ma8 = df_2.ma80[-2]
p5_close = df_2.close[-2]
n1ma2 = df_3.ma20[-1]
n1ma6 = df_3.ma60[-1]
n1ma8 = df_3.ma80[-1]
p1m_close = df_3.close[-2]
p1ma2 = df_3.ma20[-2]
p1ma6 = df_3.ma60[-2]
p1ma8 = df_3.ma80[-2]
n2hma2 = df_7.ma20[-1]
n2hma6 = df_7.ma60[-1]
n2hma8 = df_7.ma80[-1]
now = datetime.datetime.utcnow() + datetime.timedelta(hours=9)
now_date = datetime.date(now.year, now.month, now.day)
now_time = datetime.time(now.hour, now.minute, now.second)
what_day = now.weekday()
timestamp = time.mktime(datetime.datetime.strptime(str(f'{now_date} {now_time}'), '%Y-%m-%d %H:%M:%S').timetuple())
mt4 = datetime.datetime.utcnow() + datetime.timedelta(hours=3)
mt4_date = datetime.date(mt4.year, mt4.month, mt4.day)
mt4_time = datetime.time(mt4.hour, mt4.minute, mt4.second)
total_balance = exchange.fetch_balance()['USDT']['total']
total_balance2 = exchange2.fetch_balance()['USDT']['total']
total_balance5 = exchange5.fetch_balance()['USDT']['total']
print(colors.fg.blue, f'{subtitle}', colors.reset, colors.fg.green, f'{symbol}', colors.reset, f'{n_price}', colors.fg.yellow, f'{now_date} {now_time}', colors.reset)

Selenium Webscraper Unbound local error in set [ ]

I inherited a bit of Python code and I have no background. I am getting unbound local error and is probably something really silly on my part.
UnboundLocalError Traceback (most recent call last)
Input In [1], in <cell line: 372>()
368 print('\n----------------------------------------------------------------------\n')
369 ##############################################################################
--> 372 main()
Input In [1], in main()
319 Gender = p.getGender()
320 StateRes = p.getStateRes()
--> 321 children = immunte(Fname, Lname, DOB, Gender, driver)
323 if children == []:
324 not_found += 1
Input In [1], in immunte(Fname, Lname, DOB, Gender, driver)
204 except WebDriverException:
205 al = []
--> 207 return al
UnboundLocalError: local variable 'al' referenced before assignment
I have looked at this for a few days now and I can't seem to find an answer to this problem even though it is likely simple. It seems a solution to this error is a global keyword somewhere but I am not sure if this applies here as every time I tried to apply global to al = [] i got an error or same result. Any help is appreciated, thank you.
# Imports
import csv
import datetime
import os
import os.path
import time
import pandas as pd
from dateutil.parser import parse
from pandas import DataFrame
from selenium import webdriver
from selenium.common.exceptions import (NoSuchElementException,
WebDriverException)
from selenium.webdriver.support.select import Select
from selenium.webdriver.chrome.service import Service
##############################################################################
# Classes
class Person(object):
def __init__(self, measYr, MEMID, MIDSK, fname, lname, LNMSFX, DRB, GDR, STRES, meas):
self.measYr = measYr
self.MEMID = MEMID
self.MIDSK = MIDSK
self.fname = fname
self.lname = lname
self.LNMSFX = LNMSFX
self.DRB = DRB
self.GDR = GDR
self.STRES = STRES
self.meas = meas
def GTMESYR(self):
return self.measYr
def GTMEMSKY(self):
return self.MIDSK
def GTMEMID(self):
return self.MEMID
def GTFSNM(self):
return self.fname
def GTLSNM(self):
return self.lname
def GTLSTNMSF(self):
return self.LNMSFX
def GTDRB(self):
return self.DRB
def GTGDR(self):
return self.GDR
def getStateRes(self):
return self.STRES
def getMeas(self):
return self.meas
###############################################################################
# Function
def is_date(string, fuzzy=False):
try:
parse(string, fuzzy=fuzzy)
return True
except ValueError:
return False
def immunte(Fname, Lname, DRB, GDR, driver):
# work on search button
driver.find_element_by_xpath("//*[#id='edittesttest']").click()
# work on
lastname = driver.find_element_by_id("LM")
lastname.clear()
lastname.send_keys(Lname)
# work on
firstname = driver.find_element_by_id("FN")
firstname.clear()
firstname.send_keys(Fname)
# work on
birthdate = driver.find_element_by_id("DRB")
birthdate.clear()
birthdate.send_keys(DRB)
# work on advanced search button to input GDR
try:
driver.find_element_by_xpath(
"//*[#id='queryResultsForm']/table/tbody/tr/td[2]/table/tbody/tr[3]/td/table/tbody/tr[2]/td[5]/input").click()
# work on GDR selection button
obj = Select(driver.find_element_by_name("OSC"))
if GDR == 'W':
obj.select_by_index(2)
elif GDR == 'S':
obj.select_by_index(1)
else:
obj.select_by_index(3)
# work on search button
driver.find_element_by_name("cmdFindClient").click()
# two scenarios could emerge as a search result: 1, not found 2, the found
if "No were found for the requested search criteria" in driver.find_element_by_id("queryResultsForm").text:
al = []
elif "the found" in driver.find_element_by_id("queryResultsForm").text:
# work on button
driver.find_element_by_xpath(
"//*[#id='queryResultsForm']/table[2]/tbody/tr[2]/td[2]/span/label").click()
# work on pt button
driver.find_element_by_id("redirect1").click()
# work on getting rid of opt out - header
header = driver.find_elements_by_class_name("large")[1].text
if "Access Restricted" in header:
print(Fname+' '+Lname+' '+" Opt out")
al = []
elif "Information" in header:
# find the first line
first = driver.find_element_by_xpath(
"//*[#id='container']/table[3]/tbody/tr/td[2]/table[2]/tbody/tr/td/table/tbody/tr[1]/td/table/tbody/tr[5]/td[1]").text
if (first == None):
al = []
else:
even = driver.find_elements_by_class_name("evenRow")
odd = driver.find_elements_by_class_name("oddRow")
o = []
e = []
for value in odd:
o.append(value.text)
for value in even:
e.append(value.text)
length = len(o)
i = 0
al = []
# merge odd and even row together and remove the row marked with complete
while i < length:
al.append(e[i])
al.append(o[i])
i = i+1
# parse each row of information with a comma, add group name for row that are without one
for x in range(len(al)):
if is_date(al[x][1:10]):
al[x] = al[x].replace(' ', ',')
al[x] = al[x].replace(',of,', ' of ')
al[x] = group + ',' + al[x][2:]
else:
al[x] = al[x].replace(' ', ',')
al[x] = al[x].replace(',of,', ' of ')
g = al[x].split(',', 1)
group = g[0]
# work on returning to home page
driver.find_element_by_xpath(
"//*[#id='headerMenu']/table/tbody/tr/td[2]/div/a").click()
except NoSuchElementException:
al = []
except WebDriverException:
al = []
return al
def main():
# Welcome message and input info
print('\nThis is the test.')
print('You will be prompted to type .')
print('If you need to exit the script and stop its process press \'CTRL\' + \'C\'.')
file = input("\nEnter file name: ")
user = input("\nEnter username: ")
pw = input("\nEnter password: ")
date = str(datetime.date.today())
# output file
fileOutputName = 'FILELIST' + \
date.replace('-', '_') + '.csv'
fileOutputNameNotFound = 'NOTFOUNDFILELIST' + \
date.replace('-', '_') + '.csv'
fileOutput = open(fileOutputName, 'w')
fileOutputNotFound = open(fileOutputNameNotFound, 'w')
fileOutput.write('MEAS_YR,MEMLFIDSK,MEMLFID,MEMB_FRST_NM,MEMLSTNM,' +
'DRB,GNDR,RSDNC_STATE,IMUN_RGSTRY_STATE,VCCN_GRP,VCCN_ADMN_DT,DOSE_SERIES,' +
'BRND_NM,DOSE_SIZE,RCTN\n')
fileOutputNotFound.write('MEAS_YR,MEMLFIDSK,MEMLFID,MEMB_FRST_NM,MEMLSTNM,MEMB_SUFFIX,' +
'DRB,GNDR,RSDNC_STATE,IMUN_RGSTRY_STATE,VCCN_GRP,VCCN_ADMN_DT,DOSE_SERIES,' +
'BRND_NM,DOSE_SIZE,RCTN\n')
# If the file exists
try:
os.path.isfile(file)
except:
print('File Not Found\n')
df = pd.read_excel(file)
# create array of People objects and member ID
peopleArray = []
memberIdArray = []
df.dropna()
total = len(df)
not_found = 0
found = 0
# assign each record in the data frame into Person class
for i in range(total):
measYr = str(df.loc[i, "MEAS_YR"])
MEMID = str(df.loc[i, "MEMLFID"])
MIDSK = str(df.loc[i, "MEMLFIDSK"])
fname = str(df.loc[i, "MEMLFID"])
lname = str(df.loc[i, "MEMLSTNM"])
inputDate = str(df.loc[i, "DRB"])
# If date is null then assign an impossible date
if not inputDate:
DRB = '01/01/1900'
if '-' in inputDate:
DRB = datetime.datetime.strptime(
inputDate, "%Y-%m-%d %H:%M:%S").strftime('%m/%d/%Y')
else:
DRB = datetime.datetime.strptime(
str(df.loc[i, "DRB"]), '%m/%d/%Y').strftime('%m/%d/%Y')
GDR = str(df.loc[i, "GDR"])
STRES = str(df.loc[i, "STATE_RES"])
meas = str(df.loc[i, "MEAS"])
p = Person(measYr, MEMID, MIDSK, fname, lname,
LNMSFX, DRB, GDR, STRES, meas)
# append array
m = df.loc[i, "MEMLFID"]
if (m not in memberIdArray):
peopleArray.append(p)
memberIdArray.append(m)
# work on setting up driver for md immunet - mac forward slash/windows double backward slash
PATH = os.getcwd()+'\\'+'chromedriver'
s = Service(PATH)
driver = webdriver.Chrome(service = s)
driver.get("https://www.wow2.pe.org/prd-IR/portalmanager.do")
# work on login ID
username = driver.find_element_by_id("userField")
username.clear()
username.send_keys(user)
# work on password
password = driver.find_element_by_name("password")
password.clear()
password.send_keys(pw)
# work on getting to home page - where loop will start
driver.find_element_by_xpath(
"//*[#id='loginButtonForm']/div/div/table/tbody/tr[3]/td[1]/input").click()
for n in range(total):
p = peopleArray[n]
recordToWrite = ''
print('Looking up: ' + str(n)+' ' +
p.GTLSNM() + ', ' + p.GTFSNM())
MeasYr = p.GTMESYR()
MIDSK = p.GTMEMSKY()
MEMID = p.GTMEMID()
Fname = p.GTFSNM()
Lname = p.GTLSNM()
DRB = str(p.GTDRB())
GDR = p.GTGDR()
STRES = p.getStateRes()
children = immunte(Fname, Lname, DRB, GDR, driver)
if children == []:
not_found += 1
recordToWrite = MeasYr+','+MIDSK+','+MEMID+',' + Fname + \
','+Lname + ',' + ' ' + ','+DRB+','+GDR+','+STRES+','+'MD'
fileOutputNotFound.write(recordToWrite + '\n')
elif children != []:
found += 1
for x in range(len(children)):
data_element = children[x].split(",")
# if the admin date is not valid
if is_date(data_element[1]) and is_date(data_element[3]):
children[x] = ''
elif is_date(data_element[1]) and data_element[2] == 'NOT' and data_element[3] == 'VALID':
children[x] = ''
elif is_date(data_element[1]) and is_date(data_element[3]) == False:
if data_element[5] != 'No':
data_element[4] = data_element[5]
data_element[5] = ''
children[x] = ','.join(data_element[0:6])
else:
data_element[5] = ''
children[x] = ','.join(data_element[0:6])
else:
children[x] = ''
for x in range(len(children)):
if children[x] != '':
recordToWrite = MeasYr+','+MIDSK+','+MEMID+',' + \
Fname+','+Lname + ','+DRB+','+GDR+','+STRES+','+'MD'
recordToWrite = recordToWrite+','+children[x]
fileOutput.write(recordToWrite + '\n')
n = +1
fileOutput.close()
fileOutputNotFound.close()
print('\n--------------------------------OUTPUT--------------------------------')
print("Script completed.")
##############################################################################
main()
You can try this in the 'immunte' function:
def immunte(Fname, Lname, DRB, GDR, driver):
al = []
# work on search button
driver.find_element_by_xpath("//*[#id='edittesttest']").click()
# work on
lastname = driver.find_element_by_id("LM")
lastname.clear()
lastname.send_keys(Lname)
# work on
firstname = driver.find_element_by_id("FN")
firstname.clear()
firstname.send_keys(Fname)
# work on
birthdate = driver.find_element_by_id("DRB")
birthdate.clear()
birthdate.send_keys(DRB)
# work on advanced search button to input GDR
try:
driver.find_element_by_xpath(
"//*[#id='queryResultsForm']/table/tbody/tr/td[2]/table/tbody/tr[3]/td/table/tbody/tr[2]/td[5]/input").click()
# work on GDR selection button
obj = Select(driver.find_element_by_name("OSC"))
if GDR == 'W':
obj.select_by_index(2)
elif GDR == 'S':
obj.select_by_index(1)
else:
obj.select_by_index(3)
# work on search button
driver.find_element_by_name("cmdFindClient").click()
# two scenarios could emerge as a search result: 1, not found 2, the found
if "No were found for the requested search criteria" in driver.find_element_by_id("queryResultsForm").text:
return al
if "the found" in driver.find_element_by_id("queryResultsForm").text:
# work on button
driver.find_element_by_xpath(
"//*[#id='queryResultsForm']/table[2]/tbody/tr[2]/td[2]/span/label").click()
# work on pt button
driver.find_element_by_id("redirect1").click()
# work on getting rid of opt out - header
header = driver.find_elements_by_class_name("large")[1].text
if "Access Restricted" in header:
print(Fname+' '+Lname+' '+" Opt out")
return al
if "Information" in header:
# find the first line
first = driver.find_element_by_xpath(
"//*[#id='container']/table[3]/tbody/tr/td[2]/table[2]/tbody/tr/td/table/tbody/tr[1]/td/table/tbody/tr[5]/td[1]"
).text
if (first == None):
return al
even = driver.find_elements_by_class_name("evenRow")
odd = driver.find_elements_by_class_name("oddRow")
o = []
e = []
for value in odd:
o.append(value.text)
for value in even:
e.append(value.text)
length = len(o)
i = 0
al = []
# merge odd and even row together and remove the row marked with complete
while i < length:
al.append(e[i])
al.append(o[i])
i = i+1
# parse each row of information with a comma, add group name for row that are without one
for x in range(len(al)):
if is_date(al[x][1:10]):
al[x] = al[x].replace(' ', ',')
al[x] = al[x].replace(',of,', ' of ')
al[x] = group + ',' + al[x][2:]
else:
al[x] = al[x].replace(' ', ',')
al[x] = al[x].replace(',of,', ' of ')
g = al[x].split(',', 1)
group = g[0]
# work on returning to home page
driver.find_element_by_xpath(
"//*[#id='headerMenu']/table/tbody/tr/td[2]/div/a").click()
except NoSuchElementException:
pass
except WebDriverException:
pass
return al

"sqlalchemy.exc.InternalError: (psycopg2.errors.InFailedSqlTransaction) current transaction is aborted

I wrote API using Flask-SQLAlchemy which sometimes throws error "sqlalchemy.exc.InternalError: (psycopg2.errors.InFailedSqlTransaction) current transaction is aborted, commands ignored until end of transaction block" and I'm using PostgreSQL & docker containe and Ass is the sample model.
Here is my code.
#APP.route('/get_ass_info/<int:ass_id>', methods=["GET"])
def get_ass_info(ass_id):
item = Ass.query.filter_by(main_ass_id=ass_id).first()
ag_list = []
if item:
if item.sponsor != 0:
sp_obj =Ass.query.filter_by(main_ass_id=item.sponsor).first()
sp_name = sp_obj.name
else:
sp_name = 'NA'
dob_new = datetime.datetime.strptime(str(item.dob), "%Y-%m-%d")
today = datetime.date.today()
age = today.year - dob_new.year
st_obj = State.query.filter_by(id=item.ag_state).first()
if st_obj:
state_name = st_obj.name
state_id = st_obj.id
old_state_id = st_obj.old_state_id
else:
state_name = ''
state_id = 0
old_state_id = 0
dist_obj = District.query.filter_by(id=item.ag_district).first()
if dist_obj:
dist_name = dist_obj.name
dist_id = dist_obj.id
old_dist_id = dist_obj.old_district_id
else:
dist_name = ''
dist_id = 0
old_dist_id = 0
ass_dict = {'ass_id':item.id, 'name':item.name, 'rank': item.asslevel.name if
item.agentlevel_id != None else '',
'city':item.city if item.city != 'null' and item.city != None and
item.city !='None' else '',
'mobile':item.mobile_no, 'sponsor':item.sponsor, 'state':state_name,
'title':item.title,'ag_state':old_state_id,'ag_district':old_dist_id}
ag_list.append(ass_dict)
response = jsonify(ag_list)
response.status_code = 200
return response
else:
response = jsonify(ag_list)
response.status_code = 200
return response
If anyone knows the solution then let me know.

Telegram Bot reply with two or more messages

I am using pyTelegramBotAPI. I make some chain of functions using register_next_step_handler(msg, process_name_step)
It works fine, as I want.
But if I send to this bot two messages or more from user without waitining answer, hi start answering with two or more replys.
I using webhooks and CherryPy
Here is a part of my code:
# Handle '/start'
#bot.message_handler(commands=['start'])
def handle_start(message):
# get user id
user_id = message.from_user.id
# get User
user = commands.get_user(message)
# if lng not selected
if user[6] == 0:
# set user markup
user_markup = telebot.types.ReplyKeyboardMarkup(True, False)
user_markup.row('Русский язык', 'Українська мова')
msg = bot.send_message(user_id, 'Добрый день, выберите пожалуйста язык бота.\n'
'Добрий день, оберіть будь ласка мову бота.', reply_markup=user_markup)
bot.register_next_step_handler(msg, lng_select)
# if lng ru
elif user[6] == 1:
message.text = 'ru'
menu_ru(message)
# if lng ua
elif user[6] == 2:
message.text = 'ua'
menu_ua(message)
def lng_select(message):
lng = message.text
if lng == 'Русский язык':
commands.set_user_lng(message, 1)
handle_start(message)
elif lng == 'Українська мова':
commands.set_user_lng(message, 2)
handle_start(message)
else:
handle_start(message)
# ru version
def menu_ru(message):
admin = [(1, 1111111, 1)]
#get user id
user_id = message.from_user.id
# get User
user = commands.get_user(message)
user_full_name = ''
if user[2]:
user_full_name = ' ' + user[2]
# get Basket
basket = commands.make_basket(message)
if not basket:
basket = ''
user_markup = telebot.types.ReplyKeyboardMarkup(True, False)
user_markup.row('Купить журнал')
user_markup.row('Подтвердить оплату')
user_markup.row('Поменять язык')
if basket:
user_markup.row('Перейти к заказу')
user_markup.row('Очистить корзину')
if message.from_user.id == admin[0][1]:
user_markup.row('/admin')
msg = bot.send_message(user_id, 'Добро пожаловать' + user_full_name + '!\n'
+ basket +
'Что бы вы хотели сделать?', reply_markup=user_markup)
bot.register_next_step_handler(msg, process_menu_ru_step)

facebook signed request email

I have the following code:
def base64_url_decode(inp):
padding_factor = (4 - len(inp) % 4) % 4
inp += "="*padding_factor
return base64.b64decode(unicode(inp).translate(dict(zip(map(ord, u'-_'), u'+/'))))
def parse_signed_request(signed_request, secret):
l = signed_request.split('.', 2)
encoded_sig = l[0]
payload = l[1]
sig = base64_url_decode(encoded_sig)
data = json.loads(base64_url_decode(payload))
if data.get('algorithm').upper() != 'HMAC-SHA256':
log.error('Unknown algorithm')
return None
else:
expected_sig = hmac.new(secret, msg=payload, digestmod=hashlib.sha256).digest()
if sig != expected_sig:
return None
else:
log.debug('valid signed request received..')
return data
How do I use the facebook signed request data (returned from the parse_signed_request) to get the person's email address?
Here's the facebook documentation for it:
https://developers.facebook.com/docs/howtos/login/signed-request/
I tried doing :
data = parsed_signed_request(...)
data.get('registration').email
but that did not work.
What can I do?
Maybe you could try this one, this is part of my codes:
def parse_signed_request(signed_request, app_secret):
try:
l = signed_request.split('.', 2)
encoded_sig = str(l[0])
payload = str(l[1])
except IndexError:
raise ValueError("'signed_request' malformed")
sig = base64.urlsafe_b64decode(encoded_sig + "=" * ((4 - len(encoded_sig) % 4) % 4))
data = base64.urlsafe_b64decode(payload + "=" * ((4 - len(payload) % 4) % 4))
data = json.loads(data)
if data.get('algorithm').upper() != 'HMAC-SHA256':
raise ValueError("'signed_request' is using an unknown algorithm")
else:
expected_sig = hmac.new(app_secret, msg=payload, digestmod=hashlib.sha256).digest()
if sig != expected_sig:
raise ValueError("'signed_request' signature mismatch")
else:
return data
def fb_registration(request):
if request.POST:
if 'signed_request' in request.POST:
# parse and check data
data = parse_signed_request(request.POST['signed_request'], settings.FACEBOOK_APP_SECRET)
# lets try to check if user exists based on username or email
try:
check_user = User.objects.get(username=data['registration']['name'])
except:
state = "Username is already exist. Please try other account."
return HttpResponseRedirect(reverse('accounts:register'))
try:
check_user = User.objects.get(email=data['registration']['email'])
except:
state = "Email is already exist. Please use other account."
return HttpResponseRedirect(reverse('accounts:register'))
#lets create now the user
randompass = ''.join([choice('1234567890qwertyuiopasdfghjklzxcvbnm') for i in range(7)])
user = User.objects.create_user(data['registration']['name'], data['registration']['email'], randompass)
user.save()
user = authenticate(username=data['registration']['name'], password=randompass)
if user is not None:
# save in user profile his facebook id
fbid = 'http://www.facebook.com/profile.php?id=%s' % data['user_id']
r = RPXAssociation(user=user, identifier=fbid)
r.save()
login(request, user)
return HttpResponseRedirect(reverse('accounts:choose_plan'))
else:
state = "Registration request failed!"
return HttpResponseRedirect(reverse('accounts:register'))

Categories

Resources