2017-10-14 134 views
0

我正在登錄另一個網站並獲取數據的網站上工作。我正在使用燒瓶並請求庫。我的代碼從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

,可以儲存用戶名和密碼的地方(例如:flask.session),並檢查用戶是否登錄,你有充分的路線上(或也許在app.before_request)。如果沒有 - 重定向到登錄表單,否則 - 使用存儲的登錄名/密碼請求

+0

我可以將會話保存在Cookie中嗎?這是不錯的做法嗎? –

+0

btw我不想保留cookies中的用戶名和密碼 –

+0

@AdrianOleszczak查看[Flask-Session](https://pythonhosted.org/Flask-Session/),它是Flask的擴展,它增加了對Server-側會話到您的應用程序。 –