iT邦幫忙

0

req.user_agent.browser無法獲取(回傳值為NULL) (已解決)

  • 分享至 

  • xImage

我是照著課本範例打的,但卻出bug了,
程式如下:

from flask import Flask, render_template, request, escape
from vsearch import search4letters
from DBcm import UseDatabase

app = Flask(__name__)

app.config['dbconfig'] = {'host': '127.0.0.1',
                          'user': 'vsearch',
                          'password': '',
                          'database': 'vsearchlogDB', }


def log_request(req: 'flask_request', res: str) -> None:
    """Log details of the web request and the results."""

    with UseDatabase(app.config['dbconfig']) as cursor:
        _SQL = """insert into log
                  (phrase, letters, ip, browser_string, results)
                  values
                  (%s, %s, %s, %s, %s)"""
        cursor.execute(_SQL, (req.form['phrase'],
                              req.form['letters'],
                              req.remote_addr,
                              req.user_agent.browser,
                              res, ))


@app.route('/search4', methods=['POST'])
def do_search() -> 'html':
    """Extract the posted data; perform the search; return results."""
    phrase = request.form['phrase']
    letters = request.form['letters']
    title = 'Here are your results:'
    results = str(search4letters(phrase, letters))
    log_request(request, results)
    return render_template('results.html',
                           the_title=title,
                           the_phrase=phrase,
                           the_letters=letters,
                           the_results=results,)


@app.route('/')
@app.route('/entry')
def entry_page() -> 'html':
    """Display this webapp's HTML form."""
    return render_template('entry.html',
                           the_title='Welcome to search4letters on the web!')


@app.route('/viewlog')
def view_the_log() -> 'html':
    """Display the contents of the log file as a HTML table."""
    with UseDatabase(app.config['dbconfig']) as cursor:
        _SQL = """select phrase, letters, ip, browser_string, results
                  from log"""
        cursor.execute(_SQL)
        contents = cursor.fetchall()
    titles = ('Phrase', 'Letters', 'Remote_addr', 'User_agent', 'Results')
    return render_template('viewlog.html',
                           the_title='View Log',
                           the_row_titles=titles,
                           the_data=contents,)


if __name__ == '__main__':
    app.run(debug=True)

錯誤訊息: mysql.connector.errors.IntegrityError: 1048 (23000): Column 'browser_string' cannot be null

是因為req.user_agent.browser已經不能使用了嗎?(這本書滿老的)
若可以,為甚麼會無法獲取agent browser(回傳值為NULL)?

看更多先前的討論...收起先前的討論...
froce iT邦大師 1 級 ‧ 2024-01-09 08:13:02 檢舉
1. 你用的是什麼框架?沒框架的話沒辦法幫你看文件
2. 你可以用dir(req)看request裡有什麼屬性。
還是我貼整段過來 會比較清楚
froce iT邦大師 1 級 ‧ 2024-01-09 13:26:47 檢舉
https://flask.palletsprojects.com/en/3.0.x/api/#flask.Request
剛剛查了一下,.browser這邊已經被廢棄了。
https://stackoverflow.com/questions/9878020/how-do-i-get-the-user-agent-with-flask

werkzeug 2.0, the parsed data of request.user_agent has been deprecated;

要專門把瀏覽器弄出來對req.user_agent去額外處理。
不過反正是練習而已,建議直接跳過。
ccutmis iT邦高手 2 級 ‧ 2024-01-09 13:40:35 檢舉
可以試試一招就是在你執行SQL前加個判斷 req.user_agent.browser 是否為 None,例如:
browser_str = req.user_agent.browser if req.user_agent.browser != None else 'Unknown Browser'
然後在你原本執行SQL裡對應的地方,把 req.user_agent.browser 改成 browser_str
froce iT邦大師 1 級 ‧ 2024-01-09 13:52:31 檢舉
> 可以試試一招就是在你執行SQL前加個判斷 req.user_agent.browser 是否為 None

不用檢查了,一定是None,flask用來解析UA的套件werkzeug 2.0以後就不支援.bowser了。
好的 謝謝froce大
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
厚厚
iT邦新手 1 級 ‧ 2024-01-09 09:12:38

先印出 req.user_agent 看看有沒有東西吧,有東西再來看是否可以 .browser

如果沒東西,你可以改成以下試試
req.user-agent 或 req.useragent

froce iT邦大師 1 級 ‧ 2024-01-09 09:31:12 檢舉

用dir()去看就好,用猜的幹嘛...

厚厚 iT邦新手 1 級 ‧ 2024-01-09 10:31:02 檢舉

抱歉,沒注意到python標籤,以為是後端問題

req.user_agent是可以的 前幾章有使用過 也沒出bug

我要發表回答

立即登入回答