如何在URL中传递参数?

zch*_*zch 1 python url urllib2 flask

我正在制作股票应用程序,在用户输入股票之后MSFT,他们被重定向到.../stock?s=MSFT我已经成功完成这部分,但现在我需要Python来获取当前唯一的URL以便我可以解析报价(在这种情况下,MSFT如果它出来并将其保存为新变量.

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

NameError: global name 'self' is not defined
Run Code Online (Sandbox Code Playgroud)

我遇到的其他想法是使用一种形式,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')
Run Code Online (Sandbox Code Playgroud)

提前谢谢了.

Mar*_*zer 8

  1. 它是request(从烧瓶包装中导入),而不是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
    
    Run Code Online (Sandbox Code Playgroud)

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