我正在使用登录其他网站并获取数据的网站。我正在使用flask并请求库。我的代码从html模板中的输入获取登录名和密码。一切都很好,直到我试图获得另一页。然后我失去了登录会话。
views.py
from LibrusMobile import app
from flask import render_template, request
from core.forms import LoginForm
from core.utils import Site
import lxml.html
@app.route('/', methods=['GET', 'POST'])
def main_page():
form = LoginForm()
if request.method == 'POST':
username=request.form['username']
password=request.form['password']
path=Site.user_path
s=Site.login(username, password)
url='https://link.com/index'
user_response=Site.get_content(Site, s, url, path)
user=', '.join([str(x) for x in user_response])
context={
"user": user.replace("(", "- "),
}
return render_template("start_page.html", context=context)
return render_template("index.html", form=form)
@app.route('/marks')
def marks():
url='https://link.com/marks'
#Here i have a problem
return render_template("marks.html")
utils.py
import requests
import lxml.html
class Site():
user_path = '//*[@id="user-section"]/b/text()[1]'
@staticmethod
def login(login, passwd):
url = 'https://link.com/login'
with requests.session() as s:
log_in=s.get(url)
log_in_html= lxml.html.fromstring(log_in.text)
hidden_inputs = log_in_html.xpath(r'//form//input[@type="hidden"]')
form = {x.attrib["name"]: x.attrib["value"] for x in hidden_inputs}
form['login']=login
form['passwd']=passwd
request=s.post(url, data=form, stream=True)
return s
def get_content(self, session, url, path):
response=session.get(url)
b=lxml.html.fromstring(response.text)
text=b.xpath(path)
return text
答案 0 :(得分:0)
您应该在某处存储用户名和密码(例如:flask.session)并检查用户是否已登录您拥有的每条路径(或者可能是app.before_request)。如果不是 - 重定向到登录表单,否则 - 使用存储的登录/密码进行请求