flask_restful导入资源错误

时间:2018-07-23 09:51:29

标签: python flask flask-restful

我在youtube上做了以下教程:https://www.youtube.com/watch?v=s_ht4AKnWZg

这是我的代码:

from flask import Flask, request
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

class HelloWorld(Resource):
    def get(self):
        return {'about':'Hello World!'}

    def post(self):
        some_json = request.get_json()
        return {'you sent': some_json}, 201

class Multi(Resource):
    def get(self, num):
        return {'result': num*10}

api.add_resource(HelloWorld, '/')
api.add_resource(Multi, '/multi/<int:num>')

if __name__ == '__main__':
    app.run(debug=True)

现在,当我运行脚本时,出现以下错误:

/home/one/systemx/test_api$ python flask_restful.py
Traceback (most recent call last):
  File "flask_restful.py", line 2, in <module>
    from flask_restful import Resource, Api
  File "/home/one/systemx/test_api/flask_restful.py", line 2, in <module>
    from flask_restful import Resource, Api
ImportError: cannot import name Resource

代码与视频中的代码是1:1。有人知道问题出在哪里吗?

2 个答案:

答案 0 :(得分:3)

正如@tobey的注释中指出的那样,您需要将程序重命名为app.py之类的名称,因为python试图找到flask_restful并且它找到了您的程序而不是软件包

答案 1 :(得分:0)

这些安装对我有用

aniso8601 = "==8.0.0"
click = "==7.1.2"
flask = "==1.1.2"
flask-restful = "==0.3.8"
flask-sqlalchemy = "==2.4.3"
itsdangerous = "==1.1.0"
jinja2 = "==2.11.2"
markupsafe = "==1.1.1"
pytz = "==2020.1"
six = "==1.15.0"
sqlalchemy = "==1.3.18"
werkzeug = "==1.0.1"