野路子解决python import的问题

碰到了这样一个问题

就是写一个注册的后端程序

然后想分文件写,视图函数写在main.py里面

然后注册程序写在registeraction.py里面

然后在registeraction.py里写了一个add_user(username,password,email)

自己调试的时候,给这个函数传3个参数然后写入数据库是完全没有问题的

from registeraction import add_user

结果运行出来爆了一堆错误

大致就是说在连接数据库时各种参数没有设置好啊什么的

问题应该出现在py import的机制

在registeraction.py中我前面一段写的是连接数据库的操作,然后初始化了数据库实例db

而我在main.py里用add_user报的错误信息就是没有初始化db的结果

然而我不想在main.py里写上一大堆东西啊

于是。。。。啧啧啧,直接用linux shell

在main.py中这样写

@app.route('/registeraction', methods=['POST', 'GET'] )
def registeraction():
    name = request.form['username']
    email = request.form['email']
    password = request.form['password']
    action_path = config.register_action_path+' '+name+' '+email+' '+password
    os.system('python3 '+action_path)
    return 'welcome'

然后把registeraction.py稍微改下就好了

原文地址:https://www.cnblogs.com/shensobaolibin/p/8407327.html