[英]How to use os.fork with sqlalchemy core and flask using API?
I have created a user and wish to send email to the user's mail id with details: 我已经创建了一个用户,并希望将电子邮件发送给该用户的邮件ID,并提供详细信息:
def send_new_user_mail(new_user_id, plain_passwd):
'''
Send mail to new user added
'''
s1 = select([users]).where(users.c.id == new_user_id)
rs1 = conn.execute(s1).fetchone()
if rs1:
msg = Message("You are registered to use DMS",
sender=app.config['DEFAULT_MAIL_SENDER'],
recipients=[rs1[users.c.email]])
print g.referer, 'g.referer'
user_details = ('username: ' + rs1[users.c.email] + '<br>' +
'password:' + plain_passwd)
# TODO: send change password link
chg_passwd = ('<br><br>You can change password by visiting: ' +
'<a href=url_for("change_password")>' +
url_for("change_my_password", user_id=rs1[users.c.id]) +
'</a>')
chg_passwd = ''
msg.html = ('url: ' + '<a href=' + str(g.referer) + '>' +
g.referer + '</a></br><br>' + user_details +
chg_passwd)
print msg.html, 'msg.html'
try:
with app.app_context():
mail.send(msg)
return True
except Exception, e:
print e
return False
conn1.close()
return
@app.route('/sf/api/v1.0/users', methods=['POST'])
def add_user():
'''
Add a user
'''
if 'id' in session:
data = request.get_json(force=True)
trans = conn.begin()
try:
if 'first_name' in data:
data['first_name'] = data['first_name'].title()
if 'last_name' in data:
data['last_name'] = data['last_name'].title()
ins = users.insert().values(data)
rs = conn.execute(ins)
mnew_user = rs.inserted_primary_key[0]
mfolder = create_ftp_user_source_folder(mnew_user)
trans.commit()
for g in mgroups:
ins2 = users_groups.insert().values(
user=mnew_user,
group=g)
rs2 = conn1.execute(ins2)
except Exception, e:
print e
trans.rollback()
return jsonify({'message': "Invalid / duplicate details"}), 400
# user FTP source folder exists
if mfolder:
# new_child_proc = 0
new_child_proc = os.fork()
print new_child_proc, 'new_child_proc'
if new_child_proc == 0:
x = send_new_user_mail(mnew_user, plain_passwd)
os._exit(0)
else:
print 'child:', new_child_proc
return jsonify({'id': mnew_user}), 201
else:
return jsonify(
{'message': "Cannot create FTP source/already exists"}), 403
return jsonify({'message': "UNAUTHORIZED"}), 401
I tried this code, but get error: Other parts of the code also added. 我尝试了此代码,但出现错误:还添加了代码的其他部分。 If user belongs to a group(s) already, it is not added un users_groups but continues.
如果用户已经属于一个组,则不会在users_groups中添加它,而是继续。 When a new user is added a source folder is also created in the file system.
添加新用户后,还会在文件系统中创建一个源文件夹。 As suggested, I forked after storing the value in a variable and triedbut still get same error.
正如建议的那样,我将值存储在变量中后进行了分叉并尝试过,但仍然出现相同的错误。 Is there any better solution for this?
有没有更好的解决方案呢?
(psycopg2.DatabaseError) SSL error: decryption failed or bad record mac
(psycopg2.DatabaseError)SSL错误:解密失败或错误的记录mac
Some error with with connection pooling which I don't understand how to use it here. 连接池出现一些错误,我在这里不知道如何使用它。 Please guide.
请指导。 Flask v. 0.11, python 2.7, sqlalchemy core 1.0.8
Flask v.0.11,python 2.7,sqlalchemy核心1.0.8
Updating my answer as suggested by @inverio, by removing query part after fork: 按照@inverio的建议更新我的答案,方法是在fork之后删除查询部分:
def send_new_user_mail(memail_id, plain_passwd, mnew_user):
'''
Send mail to new user added to dms with url
'''
msg = Message("You are registered to use DMS",
sender=app.config['DEFAULT_MAIL_SENDER'],
recipients=[memail_id])
user_details = ('username: ' + memail_id + '<br>' +
'password:' + plain_passwd)
chg_passwd = ''
msg.html = ('url: ' + '<a href=' + str(g.referer) + '>' +
g.referer + '</a></br><br>' + user_details +
chg_passwd)
try:
with app.app_context():
mail.send(msg)
return True
except Exception, e:
print e
return False
conn1.close()
return
@app.route('/sf/api/v1.0/users', methods=['POST'])
def add_user():
'''
Add a user and select his group(s)
'''
if 'id' in session:
if session['email'].split("@")[0] == 'ytms.admin' and \
session['flag'] is True:
mgroups = []
mnew_user = None
mfolder = None
memail = None
data = request.get_json(force=True)
if data['password']:
# pass
plain_passwd = data['password']
mypass = pwd_context.encrypt(data['password'])
data['password'] = mypass
if "groups" not in data:
return jsonify({'message': "Cannot add without group(s)"}), 400
for g in data["groups"]:
mgroups.append(g)
del data["groups"]
print data, 'data'
trans = conn.begin()
try:
if 'first_name' in data:
data['first_name'] = data['first_name'].title()
if 'last_name' in data:
data['last_name'] = data['last_name'].title()
ins = users.insert().values(data)
rs = conn.execute(ins)
mnew_user = rs.inserted_primary_key[0]
mfolder = create_ftp_user_source_folder(mnew_user)
memail = data['email']
trans.commit()
for g in mgroups:
ins2 = users_groups.insert().values(
user=mnew_user,
group=g)
rs2 = conn1.execute(ins2)
except Exception, e:
print e
trans.rollback()
return jsonify({'message': "Invalid / duplicate details"}), 400
# user FTP source folder exists
if mfolder:
new_child_proc = os.fork()
if new_child_proc == 0:
x = send_new_user_mail(memail, plain_passwd, mnew_user)
os._exit(0)
else:
print 'child:', new_child_proc
return jsonify({'id': mnew_user}), 201
else:
return jsonify(
{'message': "Cannot create FTP source/already exists"}), 403
return jsonify({'message': "UNAUTHORIZED"}), 401
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.