我最近购买了RealPython来了解Python和Web开发。但是,我遇到了一个障碍,我认为这是我机器上的Python配置问题。任何帮助都是非常有用的。
所以我有一个名为app.py的Flask文档,类似于RealPython's github app.py
# --- Flask Hello World ---#
# import the Flask class from the flask module
from flask import Flask
# create the application object
app = Flask(__name__)
# use decorators to link the function to a url
@app.route("/")
@app.route("/hello")
# define the view using a function, which returns a string
def hello_world():
return "Hello, World!"
# dynamic route
@app.route("/test/<search_query>")
def search(search_query):
return search_query
# dynamic route with an int type
@app.route("/integer/<int:value>")
def type(value):
print value + 1
return "correct"
# dynamic route with an float type
@app.route("/float/<float:value>")
def type(value):
print value + 1
return "correct"
# dynamic route that accepts slashes
@app.route("/path/<path:value>")
def type(value):
print value
return "correct"
# start the development server using the run() method
if __name__ == "__main__":
app.run()
我很遗憾在尝试运行应用时收到此错误:
machine:flask-hello-world machine$ source env/bin/activate
(env)machine:flask-hello-world machine$ python app.py
Traceback (most recent call last):
File "app.py", line 29, in <module>
@app.route("/float/<float:value>")
File "/Volumes/disk2/Home/Library/RealPython/flask-hello-world/env/lib/python2.7/site-packages/flask/app.py", line 1013, in decorator
self.add_url_rule(rule, endpoint, f, **options)
File "/Volumes/disk2/Home/Library/RealPython/flask-hello-world/env/lib/python2.7/site-packages/flask/app.py", line 62, in wrapper_func
return f(self, *args, **kwargs)
File "/Volumes/disk2/Home/Library/RealPython/flask-hello-world/env/lib/python2.7/site-packages/flask/app.py", line 984, in add_url_rule
'existing endpoint function: %s' % endpoint)
AssertionError: View function mapping is overwriting an existing endpoint function: type
Pip冻结将这些作为virtualenv env
的要求。 Python 2.7就是安装的。
Flask==0.10.1
Jinja2==2.7.3
MarkupSafe==0.23
Werkzeug==0.9.6
itsdangerous==0.24
wsgiref==0.1.2
我能够让代码运行的唯一方法是改变def类型。不过不应该这样做......
# dynamic route with an int type
@app.route("/integer/<int:value>")
def type(value):
print value + 1
return "correct"
# dynamic route with an float type
# change to type1 so dev server will spool up
@app.route("/float/<float:value>")
def type1(value):
print value + 1
return "correct"
# dynamic route that accepts slashes
# change to type2 so dev server will spool up
@app.route("/path/<path:value>")
def type2(value):
print value
return "correct"
答案 0 :(得分:15)
所以,你找到了解决方案:它是命名空间问题。您有三个相互冲突的函数 - def type
。当您使用不同的名称重命名它们时,这解决了问题。
顺便说一句,我是Real Python的作者。现在纠正。
干杯!
答案 1 :(得分:1)
您可以将多个地图指向同一方法:
@app.route("/integer/<int:value>")
@app.route("/float/<float:value>")
def var_type(value):
print value + 1
return "correct"
您不应将方法命名为type
,因为它是内置类型类的名称:
模块
__builtin__
中的类类型帮助:
class type(object)
| type(object) -> the object's type
| type(name, bases, dict) -> a new type
答案 2 :(得分:0)
您的三种方法具有相同的名称。包装器使用方法的名称来进行映射