我无法从另一个文件夹导入函数,它给出了导入错误(ImportError:无法导入名称“ token_required”)

时间:2018-08-01 11:35:59

标签: python flask pymongo

我是python和flask的新手,试图将名为Users_service的文件夹中存在的route_user.py文件中的功能导入存在于名为JD_service的文件夹中的route_jd.py文件中,并且同时存在Users_service和JD_service文件夹在名为blue的文件夹中。

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的新手,请帮助我如何摆脱此错误?我做错了什么? 预先感谢!

2 个答案:

答案 0 :(得分:0)

两种方式:

  1. 将Users_Service定义为模块,即在文件夹 Users_Service
  2. 中创建文件__init__.py
  3. __init__.py内创建导入import * from blue.Users_Service.route_users
  4. route_jd.py 中:from blue.Users_Service import token_required

那是您要从模块 blue.Users_Service 导入,在您的情况下,该模块不是模块,而只是文件夹

其他方法是直接导入:

from blue.Users_Service.route_users import token_required

答案 1 :(得分:0)

您在导入route_jd.py文件时忘记输入文件名:

    from blue.Users_Service.route_users import token_required