Skip to main content
 首页 » 编程设计

python之如何获取在url中传递的参数

2025年05月04日11webabcd

我正在制作一个股票应用程序,在用户输入股票后,例如 MSFT,他们将被重定向到 .../stock?s=MSFT我已经成功完成了这一部分,但现在我需要 Python 获取这个当前唯一的 URL,以便我可以解析引号(在本例中为 MSFT)并将其另存为新的多变的。

我能想到的最简单的方法就是获取当前的 URL,尽管我似乎找不到办法做到这一点;使用 self.request... 但这返回了错误:

NameError: global name 'self' is not defined 

我遇到的其他想法是使用 urllib 的形式,因为它包含特定的 .request_qs() 方法,尽管这需要我将 URL 传递为一个参数,由于库存的变化,每次都应该是唯一的。

这是我目前拥有的 Python:

@app.route('/', methods=['GET', 'POST']) 
def home_search(): 
    if request.method == 'POST': 
            st = request.form['s'] 
            return redirect(url_for('stock')+'?s='+st) 
 
    return render_template('stk.html')  
 
@app.route('/stock', methods=['GET', 'POST']) 
def stock(): 
    #here I need to save the variable 'name' as the current URL. I can parse it later. 
    url="http://finance.yahoo.com/d/quotes.csv?s="+name"&f=snl1" 
    text=urllib2.urlopen(url).read() 
 
    return render_template('stock.html') 

非常感谢。

请您参考如下方法:

  1. 是request(从flask包中引入),不是self.request

  2. Flask 文档一如既往地提供了有关 URL 中变量的详尽文档:http://flask.pocoo.org/docs/quickstart/#variable-rules

    @app.route('/user/<username>') 
    def show_user_profile(username): 
        # show the user profile for that user 
        return 'User %s' % username 
    

那时,您应该阅读 Flask 文档中的整个快速入门:http://flask.pocoo.org/docs/quickstart/