【问题标题】:How can I get a parameter passed in the url?如何获取在 url 中传递的参数?
【发布时间】:2012-10-09 07:43:29
【问题描述】:

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

非常感谢。

【问题讨论】:

  • 请提供更多代码。看起来你正在混合方法和功能:)
  • @MortenJensen 谢谢;我已经更新了我的答案
  • 我添加了一个答案。如果您已经在home_search 中使用了request 对象,您究竟为什么会想到self.request
  • @MarkusUnterwaditzer 很好的问题,但感谢您的回答和解释。

标签: python url flask urllib2


【解决方案1】:

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

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

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

【讨论】:

  • 我现在有关于我需要在哪里获取 URL 的评论是我尝试过 name = self.requests 的地方 - 我现在将复制该错误并再次更详细地发布它。
  • 你只需要访问 request 变量 :) 我认为你很接近
【解决方案2】:
  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/

【讨论】:

    猜你喜欢
    • 2018-07-05
    • 2020-08-31
    • 2013-06-29
    • 2011-09-11
    • 1970-01-01
    • 2015-04-03
    • 1970-01-01
    • 1970-01-01
    • 2015-07-09
    相关资源
    最近更新 更多