标签归档:url-parameters

Python字典到URL参数

问题:Python字典到URL参数

我正在尝试将Python字典转换为用作URL参数的字符串。我敢肯定,有一种更好的,更Python化的方法可以做到这一点。它是什么?

x = ""
for key, val in {'a':'A', 'b':'B'}.items():
    x += "%s=%s&" %(key,val)
x = x[:-1]

I am trying to convert a Python dictionary to a string for use as URL parameters. I am sure that there is a better, more Pythonic way of doing this. What is it?

x = ""
for key, val in {'a':'A', 'b':'B'}.items():
    x += "%s=%s&" %(key,val)
x = x[:-1]

回答 0

使用urllib.urlencode()。它采用键值对字典,然后将其转换为适合网址的形式(例如,key1=val1&key2=val2)。

如果您使用的是Python3,请使用 urllib.parse.urlencode()

如果要使用重复的参数创建URL,例如:p=1&p=2&p=3您有两个选择:

>>> import urllib
>>> a = (('p',1),('p',2), ('p', 3))
>>> urllib.urlencode(a)
'p=1&p=2&p=3'

或者,如果您想使用重复的参数创建网址:

>>> urllib.urlencode({'p': [1, 2, 3]}, doseq=True)
'p=1&p=2&p=3'

Use urllib.urlencode(). It takes a dictionary of key-value pairs, and converts it into a form suitable for a URL (e.g., key1=val1&key2=val2).

If you are using Python3, use urllib.parse.urlencode()

If you want to make a URL with repetitive params such as: p=1&p=2&p=3 you have two options:

>>> import urllib
>>> a = (('p',1),('p',2), ('p', 3))
>>> urllib.urlencode(a)
'p=1&p=2&p=3'

or if you want to make a url with repetitive params:

>>> urllib.urlencode({'p': [1, 2, 3]}, doseq=True)
'p=1&p=2&p=3'

回答 1

使用第三方Python URL操作库furl

f = furl.furl('')
f.args = {'a':'A', 'b':'B'}
print(f.url) # prints ... '?a=A&b=B'

如果需要重复的参数,可以执行以下操作:

f = furl.furl('')
f.args = [('a', 'A'), ('b', 'B'),('b', 'B2')]
print(f.url) # prints ... '?a=A&b=B&b=B2'

Use the 3rd party Python url manipulation library furl:

f = furl.furl('')
f.args = {'a':'A', 'b':'B'}
print(f.url) # prints ... '?a=A&b=B'

If you want repetitive parameters, you can do the following:

f = furl.furl('')
f.args = [('a', 'A'), ('b', 'B'),('b', 'B2')]
print(f.url) # prints ... '?a=A&b=B&b=B2'

回答 2

在我看来,这似乎更像Pythonic,并且不使用任何其他模块:

x = '&'.join(["{}={}".format(k, v) for k, v in {'a':'A', 'b':'B'}.items()])

This seems a bit more Pythonic to me, and doesn’t use any other modules:

x = '&'.join(["{}={}".format(k, v) for k, v in {'a':'A', 'b':'B'}.items()])

如何使用Flask从URL获取命名参数?

问题:如何使用Flask从URL获取命名参数?

当用户访问在我的flask应用程序上运行的URL时,我希望Web服务能够处理问号后指定的参数:

http://10.1.1.1:5000/login?username=alex&password=pw1

#I just want to be able to manipulate the parameters
@app.route('/login', methods=['GET', 'POST'])
def login():
    username = request.form['username']
    print(username)
    password = request.form['password']
    print(password)

When the user accesses this URL running on my flask app, I want the web service to be able to handle the parameters specified after the question mark:

http://10.1.1.1:5000/login?username=alex&password=pw1

#I just want to be able to manipulate the parameters
@app.route('/login', methods=['GET', 'POST'])
def login():
    username = request.form['username']
    print(username)
    password = request.form['password']
    print(password)

回答 0

使用request.args得到解析查询字符串的内容:

from flask import request

@app.route(...)
def login():
    username = request.args.get('username')
    password = request.args.get('password')

Use request.args to get parsed contents of query string:

from flask import request

@app.route(...)
def login():
    username = request.args.get('username')
    password = request.args.get('password')

回答 1

URL参数可在中使用request.args,它是具有方法的ImmutableMultiDict,具有get默认值(default)和类型(type)的可选参数-这是可调用的方法,可将输入值转换为所需的格式。(有关更多详细信息,请参见该方法文档。)

from flask import request

@app.route('/my-route')
def my_route():
  page = request.args.get('page', default = 1, type = int)
  filter = request.args.get('filter', default = '*', type = str)

上面的代码示例:

/my-route?page=34               -> page: 34  filter: '*'
/my-route                       -> page:  1  filter: '*'
/my-route?page=10&filter=test   -> page: 10  filter: 'test'
/my-route?page=10&filter=10     -> page: 10  filter: '10'
/my-route?page=*&filter=*       -> page:  1  filter: '*'

The URL parameters are available in request.args, which is an ImmutableMultiDict that has a get method, with optional parameters for default value (default) and type (type) – which is a callable that converts the input value to the desired format. (See the documentation of the method for more details.)

from flask import request

@app.route('/my-route')
def my_route():
  page = request.args.get('page', default = 1, type = int)
  filter = request.args.get('filter', default = '*', type = str)

Examples with the code above:

/my-route?page=34               -> page: 34  filter: '*'
/my-route                       -> page:  1  filter: '*'
/my-route?page=10&filter=test   -> page: 10  filter: 'test'
/my-route?page=10&filter=10     -> page: 10  filter: '10'
/my-route?page=*&filter=*       -> page:  1  filter: '*'

回答 2

您还可以在视图定义的URL上使用方括号<>,此输入将进入您的视图函数参数

@app.route('/<name>')
def my_view_func(name):
    return name

You can also use brackets <> on the URL of the view definition and this input will go into your view function arguments

@app.route('/<name>')
def my_view_func(name):
    return name

回答 3

如果您在URL中传递了一个参数,则可以按照以下步骤进行操作

from flask import request
#url
http://10.1.1.1:5000/login/alex

from flask import request
@app.route('/login/<username>', methods=['GET'])
def login(username):
    print(username)

如果您有多个参数:

#url
http://10.1.1.1:5000/login?username=alex&password=pw1

from flask import request
@app.route('/login', methods=['GET'])
    def login():
        username = request.args.get('username')
        print(username)
        password= request.args.get('password')
        print(password)

在POST请求的情况下,您尝试执行的操作将参数作为表单参数传递并且不出现在URL中。如果您实际上正在开发登录API,建议您使用POST请求而不是GET,并将数据公开给用户。

如果有职位要求,它将按以下方式工作:

#url
http://10.1.1.1:5000/login

HTML片段:

<form action="http://10.1.1.1:5000/login" method="POST">
  Username : <input type="text" name="username"><br>
  Password : <input type="password" name="password"><br>
  <input type="submit" value="submit">
</form>

路线:

from flask import request
@app.route('/login', methods=['POST'])
    def login():
        username = request.form.get('username')
        print(username)
        password= request.form.get('password')
        print(password)

If you have a single argument passed in the URL you can do it as follows

from flask import request
#url
http://10.1.1.1:5000/login/alex

from flask import request
@app.route('/login/<username>', methods=['GET'])
def login(username):
    print(username)

In case you have multiple parameters:

#url
http://10.1.1.1:5000/login?username=alex&password=pw1

from flask import request
@app.route('/login', methods=['GET'])
    def login():
        username = request.args.get('username')
        print(username)
        password= request.args.get('password')
        print(password)

What you were trying to do works in case of POST requests where parameters are passed as form parameters and do not appear in the URL. In case you are actually developing a login API, it is advisable you use POST request rather than GET and expose the data to the user.

In case of post request, it would work as follows:

#url
http://10.1.1.1:5000/login

HTML snippet:

<form action="http://10.1.1.1:5000/login" method="POST">
  Username : <input type="text" name="username"><br>
  Password : <input type="password" name="password"><br>
  <input type="submit" value="submit">
</form>

Route:

from flask import request
@app.route('/login', methods=['POST'])
    def login():
        username = request.form.get('username')
        print(username)
        password= request.form.get('password')
        print(password)

回答 4

网址:

http://0.0.0.0:5000/user/name/

码:

@app.route('/user/<string:name>/', methods=['GET', 'POST'])
def user_view(name):
    print(name)

(编辑:删除格式字符串中的空格)

url:

http://0.0.0.0:5000/user/name/

code:

@app.route('/user/<string:name>/', methods=['GET', 'POST'])
def user_view(name):
    print(name)

(Edit: removed spaces in format string)


回答 5

真的很简单。让我将此过程分为两个简单步骤。

  1. 在html模板上,您将用户名和密码的名称标签声明为

    <form method="POST">
    <input type="text" name="user_name"></input>
    <input type="text" name="password"></input>
    </form>
  2. 然后,将代码修改为:

    from flask import request
    
    @app.route('/my-route', methods=['POST']) #you should always parse username and 
    # password in a POST method not GET
    def my_route():
      username = request.form.get("user_name")
      print(username)
      password = request.form.get("password")
      print(password)
    #now manipulate the username and password variables as you wish
    #Tip: define another method instead of methods=['GET','POST'], if you want to  
    # render the same template with a GET request too

It’s really simple. Let me divide this process into two simple steps.

  1. On the html template you will declare name tag for username and password as

    <form method="POST">
    <input type="text" name="user_name"></input>
    <input type="text" name="password"></input>
    </form>
    
  2. Then, modify your code as:

    from flask import request
    
    @app.route('/my-route', methods=['POST']) #you should always parse username and 
    # password in a POST method not GET
    def my_route():
      username = request.form.get("user_name")
      print(username)
      password = request.form.get("password")
      print(password)
    #now manipulate the username and password variables as you wish
    #Tip: define another method instead of methods=['GET','POST'], if you want to  
    # render the same template with a GET request too
    

回答 6

使用request.args.get(param),例如:

http://10.1.1.1:5000/login?username=alex&password=pw1
@app.route('/login', methods=['GET', 'POST'])
def login():
    username = request.args.get('username')
    print(username)
    password = request.args.get('password')
    print(password)

这是代码的引用链接。

Use request.args.get(param), for example:

http://10.1.1.1:5000/login?username=alex&password=pw1
@app.route('/login', methods=['GET', 'POST'])
def login():
    username = request.args.get('username')
    print(username)
    password = request.args.get('password')
    print(password)

Here is the referenced link to the code.