如何在URL中传递参数?

时间:2012-10-18 18:45:33

标签: python url flask urllib2

我正在制作股票应用程序,在用户输入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')

非常感谢提前。

2 个答案:

答案 0 :(得分: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
    
  3. 在那种情况下,您应该阅读Flask文档中的整个快速入门:http://flask.pocoo.org/docs/quickstart/

答案 1 :(得分:1)

您尚未发布有关错误发生位置的任何信息:)我无法查看您尝试访问self.requests的位置。

查看其他Flask应用,您似乎应该只访问request

看一下这些例子:https://github.com/mitsuhiko/flask/tree/master/examples