我无法从另一个文件夹导入函数,它导致导入错误(ImportError:无法导入名称'token_required')
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了我无法从另一个文件夹导入函数,它导致导入错误(ImportError:无法导入名称'token_required')相关的知识,希望对你有一定的参考价值。
我是python和flask的新手,试图将一个名为Users_service的文件夹中的route_user.py文件中的函数导入到一个route_jd.py文件中,该文件存在于名为JD_service的文件夹中,文件夹Users_service和JD_service都存在于文件夹中名为蓝色。
route_users.py文件
from flask import jsonify,request,Blueprint,make_response
from flask_pymongo import PyMongo
from blue import app
from werkzeug.security import generate_password_hash,check_password_hash
import uuid
import jwt
import datetime
from functools import wraps
app.config['SECRET_KEY'] = 'itshouldbehidden'
app.config['MONGO_URI'] = "mongodb://localhost:27017/mydata"
mongo = PyMongo(app)
mod = Blueprint('Users_Service',__name__)
def token_required(f):
@wraps(f)
def decorated(*args,**kwargs):
token = None
if 'x-access-token' in request.headers:
token = request.headers['x-access-token']
if not token:
return jsonify({'message':'token is missing!'}),401
try:
data = jwt.decode(token, app.config['SECRET_KEY'])
print(data)
jd = mongo.db.hashed_User
current_user = jd.find_one({'public_id':data['public_id']})
print(current_user)
except:
return jsonify({'message':'Token is invalid'}),401
return f(current_user,*args,**kwargs)
return decorated
@mod.route('/add',methods=['POST'])
@token_required
def create_user(current_user):
if not current_user['admin']:
return jsonify({'message':'cannot perform that function'})
jd = mongo.db.hashed_User
data = request.get_json()
try:
hashed_password = generate_password_hash(data['password'],method='sha256')
jd.insert({"public_id":str(uuid.uuid4()),"name":data['name'],"password":hashed_password,"admin":False})
output = 'new user created!'
except:
output = 'please fill all the fields and try again'
return jsonify({'message':output})
@mod.route('/all',methods=['GET'])
@token_required
def get_all_users(current_user):
if not current_user['admin']:
return jsonify({'message':'cannot perform that function'})
jd = mongo.db.hashed_User
output = []
for q in jd.find():
output1={'User Name': q['name'],'Password':q['password'],'Public ID':q['public_id'],'Admin':q['admin']}
output.append(output1)
return jsonify({'Users':output})
@mod.route('/<public_id>',methods=['GET'])
@token_required
def get_one_user(current_user,public_id):
if not current_user['admin']:
return jsonify({'message':'cannot perform that function'})
jd = mongo.db.hashed_User
user = jd.find_one({'public_id':public_id})
if not user:
return jsonify({'message':'No such User exists'})
user_data={'User Name': user['name'],'Password':user['password'],'Public ID':user['public_id'],'Admin':user['admin']}
return jsonify({'Users':user_data})
@mod.route('/admin_promote/<public_id>',methods=['PUT'])
@token_required
def Promote_to_admin(current_user,public_id):
if not current_user['admin']:
return jsonify({'message':'cannot perform that function'})
jd = mongo.db.hashed_User
user = jd.find_one({'public_id':public_id})
if not user:
return jsonify({'message':'No such User exists'})
whereto = { "public_id":public_id}
newvalues={"$set":{'admin':True}}
jd.update_one(whereto,newvalues)
return jsonify({'message':'promoted to admin successfully'})
@mod.route('/delete/<public_id>',methods=['DELETE'])
@token_required
def delete_user(current_user,public_id):
if not current_user['admin']:
return jsonify({'message':'cannot perform that function'})
jd = mongo.db.hashed_User
user = jd.find_one({'public_id':public_id})
if not user:
return jsonify({'message':'No such User exists'})
jd = mongo.db.hashed_User
jd.delete_one({'public_id':public_id})
return jsonify({'message':'Deleted successfully'})
@mod.route('/auth/login',methods=['GET'])
def login():
auth=request.authorization
print(auth)
if not auth or not auth.username or not auth.password:
return make_response('Could not very',401,{'WWW-Authenticate':'Basic realm="Login required!"'})
jd = mongo.db.hashed_User
user = jd.find_one({'name':auth.username})
if not user:
return make_response('Could not very',401,{'WWW-Authenticate':'Basic realm="Login required!"'})
if check_password_hash(user['password'],auth.password):
token = jwt.encode({'public_id' : user['public_id'],'exp':datetime.datetime.utcnow() + datetime.timedelta(minutes=30)},app.config['SECRET_KEY'])
return jsonify({'token' : token.decode('UTF-8')})
return make_response('Could not very',401,{'WWW-Authenticate':'Basic realm="Login required!"'})
route_jd.py文件
from flask import jsonify,request,Blueprint
from flask_pymongo import PyMongo
from blue import app
from blue.Users_Service import token_required # getting an error here
app.config['MONGO_URI'] = "mongodb://localhost:27017/mydata"
mongo = PyMongo(app)
mod = Blueprint('JD_Service',__name__)
@mod.route('/',methods=['GET'])
@token_required
def get_all_jds():
if not current_user['admin']:
return jsonify({'message':'cannot perform that function'})
jd = mongo.db.User11
output = []
.
.
.
.some more codes below
我得到的错误是
Traceback (most recent call last):
File "run.py", line 1, in <module>
from blue import app
File "D:\flask_resource\blue\__init__.py", line 5, in <module>
from blue.JD_Service.route_jd import mod
File "D:\flask_resource\blue\JD_Service\route_jd.py", line 4, in <module>
from blue.Users_Service import token_required
ImportError: cannot import name 'token_required'
因为我是python和flask的新手,请帮我解决如何摆脱这个错误?我做错了什么?提前致谢!
答案
您在route_jd.py文件中导入时忘记放置文件名:
from blue.Users_Service.route_users import token_required
另一答案
两种方式:
- 将Users_Service定义为模块,即在Users_Service文件夹中创建文件
__init__.py
- 在
__init__.py
内创建进口import * from blue.Users_Service.route_users
- 在route_jd.py:
from blue.Users_Service import token_required
那是你试图从模块blue.Users_Service
导入,在你的情况下,它不是一个模块,而只是一个文件夹
其他方式是直接导入:
from blue.Users_Service.route_users import token_required
以上是关于我无法从另一个文件夹导入函数,它导致导入错误(ImportError:无法导入名称'token_required')的主要内容,如果未能解决你的问题,请参考以下文章