How can i use await async function in Django view function? - python

in my django project, I want the function that generates the returned result not to process the other request before it ends. How can I provide this?
views.py
def orderresult(request):
if request.method == 'POST':
username = request.POST["username"]
order = request.POST["order"]
doubleResult = ResultsFormView(order,username).resultview() # ====> Async await function
result = doubleResult[0]
boolresult = doubleResult[1]
context = {
"result" : result,
"boolresult" : boolresult
}
return render(request, 'npages/result.html', context=context)
I tried something like this but it doesn't work.
async def orderresult(request):
if request.method == 'POST':
username = request.POST["username"]
order = request.POST["order"]
doubleResult = await ResultsFormView(order,username).resultview() # ====> Async await function
result = doubleResult[0]
boolresult = doubleResult[1]
context = {
"result" : result,
"boolresult" : boolresult
}
return render(request, 'npages/result.html', context=context)

Related

MultiValueDictKeyError at / 'name'

enter image description here
i just want to fetch the data from my website and record it to my django databae
this my views.py code :
def index(request):
feature1 = Feature.objects.all()
Appnt = Appointment.objects.all()
if request.method == 'GET':
Appnt.name = request.GET['name']
Appnt.email = request.GET['email']
Appnt.phone = request.GET['phone']
Appnt.Adate = request.GET['date']
Appnt.Dept = request.GET['department']
Appnt.Doc = request.GET['doctor']
Appnt.message = request.GET['message']
contaxt = {
'feature1' : feature1,
'Appointment' : Appnt
}
return render(request, 'index.html', contaxt)
If the parameters can be blank (not passed), use get:
def index(request):
feature1 = Feature.objects.all()
Appnt = Appointment.objects.all()
if request.method == 'GET':
Appnt.name = request.GET.get('name')
Appnt.email = request.GET.get('email')
Appnt.phone = request.GET.get('phone')
Appnt.Adate = request.GET.get('date')
Appnt.Dept = request.GET.get('department')
Appnt.Doc = request.GET.get('doctor')
Appnt.message = request.GET.get('message')
context = {
'feature1' : feature1,
'Appointment' : Appnt
}
return render(request, 'index.html', context)
If the parameters should not be blank, the problem is how the client makes the request.

JSON Token won't load the value after being verified

Once I get to the verify_token function it keeps executing the except statement instead of returning the value in 'id_user' and I'm not sure why. I am using these libraries. flask-login, sqlalchemy, itsdangerous for jsonwebserializer, and wtforms.
Functions
def get_reset_token(user):
serial = Serializer(app.config['SECRET_KEY'], expires_in=900) # 15 mins in seconds
return serial.dumps({'id_user':user.id}).decode('utf-8')
def verify_token(token):
serial = Serializer(app.config['SECRET_KEY'])
try:
user_id = serial.load(token)['id_user']
except:
return None
return Users.query.get('id_user')
def send_mail(user):
token = get_reset_token(user)
message = Message('Password Reset Request', recipients = [user.email], sender='noreply#gmail.com')
message.body= f'''
To Reset your password, click the following link:
{url_for('reset_token', token = token, _external = True)}
If you did not send this email, please ignore this message.
'''
mail.send(message)
ROUTES
#app.route('/password_reset', methods = ['GET', 'POST'])
def password_reset():
form = Password_request()
if request.method == "POST":
if form.validate_on_submit:
user = Users.query.filter_by(email = form.email.data).first()
send_mail(user)
flash('Check your email. Password change request has been sent')
return redirect(url_for('login'))
else:
flash('Your email was not linked to an account')
return render_template('password_reset.html', form = form)
#app.route('/password_reset/<token>', methods = ['GET', 'POST'])
def reset_token(token):
user = verify_token(token)
if user == None:
flash('The token is invalid or expired')
return redirect(url_for('password_reset'))
form = Password_success()
if form.validate_on_submit:
hashed_password=generate_password_hash(form.password.data, method = 'sha256')
user.password = hashed_password
db.session.commit()
flash('Your password has been updated!')
return redirect(url_for('signup'))
def verify_token(token):
serial = Serializer(app.config['SECRET_KEY'])
try:
user_id = serial.load(token)['id_user']
except:
return None
return Users.query.get('id_user') # this looks wrong
Shouldn't the last line of verify_token be return Users.query.get(user_id)? You're assigning the value of the token to that variable , then ignoring it and telling SQLAlchemy to find a record with the ID of the string value 'id_user' which I doubt is what you're intending to do.
def verify_token(token):
serial = Serializer(app.config['SECRET_KEY'])
try:
user_id = serial.load(token)['id_user']
except:
return None
return Users.query.get(user_id) # What happens when you change this?

Getting an error: AttributeError: 'Flask' object has no attribute 'login_manager'

I am trying to run my flask app, but every time I load my index page, it gives me the error:
AttributeError: 'Flask' object has no attribute 'login_manager'.
It works before I put in this specific code
bp = flask.Blueprint("bp", __name__, template_folder="./build")
#bp.route('/index')
#login_required
def index():
# TODO: insert the data fetched by your app main page here as a JSON
DATA = {"your": "data here"}
data = json.dumps(DATA)
return flask.render_template(
"index.html",
data=data,
)
app.register_blueprint(bp)
This is my current code where it does work
#app.route("/index", methods=["GET", "POST"])
def index():
global current_user
if not current_user:
return flask.redirect(flask.url_for("login"))
if flask.request.method == "GET":
track_name, genius_link, track_artist, track_image, track_url = render()
# If user has no favorite artists, redirect back to profile.
if track_name == None:
return flask.redirect(flask.url_for("profile"))
return flask.render_template(
"index.html",
variable=track_name,
variable1=genius_link,
variable2=track_artist,
variable3=track_image,
variable4=track_url,
)
else:
valid_artist = validate_and_insert_artist(flask.request.form["artistId"])
if not valid_artist:
return flask.render_template("index.html", error=True)
else:
track_name, genius_link, track_artist, track_image, track_url = render()
# If user has no favorite artists, redirect back to profile.
if track_name == None:
return flask.redirect(flask.url_for("profile"))
return flask.render_template(
"index.html",
variable=track_name,
variable1=genius_link,
variable2=track_artist,
variable3=track_image,
variable4=track_url,
)
I am not sure why as soon as I put in the blueprint code, it stops working and gives me that error
This is my login.html
#app.route("/login", methods=["GET", "POST"])
def login():
global current_user
if current_user:
return flask.redirect(flask.url_for("profile"))
if flask.request.method == "GET":
return flask.render_template("login.html")
if flask.request.method == "POST":
username = flask.request.form["username"]
cursor.execute(
"SELECT user_name FROM public.users WHERE user_name = %s", [username]
)
results = cursor.fetchall()
if len(results) != 0: # if a user exists, "log" them in
current_user = username
return flask.redirect(flask.url_for("profile"))
else:
return flask.render_template("login.html", error=True)
You need to read the Flask documentation for #login_required. As soon as you've added a method that requires the user to be logged in, you need to provide a method by which the user can log in.
Or perhaps you just want to delete the #login_required?

How do I use identation in try block properly?

This piece of code is getting me an error of invalid syntax on first return render line. I guess I have messed up my identation, but i do not know how exactly I did.
def searchView(request):
if request.method == 'GET':
query = request.GET.get('search')
try:
result = Vacancy.objects.filter(name__icontains = query)
return render(request, "search.html", {'vacancies': result })
else:
return render(request, "search.html", {})
your try
should have except
do this
try:
#something
except:
pass
i.e
def searchView(request):
if request.method == 'GET':
query = request.GET.get('search')
try:
result = Vacancy.objects.filter(name__icontains = query)
except:
pass
return render(request, "search.html", {'vacancies': result })
else:
return render(request, "search.html", {})

Commit a variable to the next function

I just simple want to pass the emailadress from def send_username to the second def username_is_send. How do I do it? How can I pass the variable to the next def?
#csrf_protect
def send_username(request, template_name='auth/user/registration/send_username_form.html',
email_template_name='auth/user/registration/send_username_email.html',
send_username_form=SendUsernameForm, post_reset_redirect=None):
if post_reset_redirect is None:
post_reset_redirect = reverse('auth.user.registration.views.username_is_send')
if request.method == "POST":
form = send_username_form(request.POST)
if form.is_valid():
opts = {}
opts['use_https'] = request.is_secure()
opts['email_template_name'] = email_template_name
opts['request'] = request
form.send_mail_now(**opts)
return HttpResponseRedirect(post_reset_redirect)
else:
form = send_username_form()
return render_to_response(template_name, {
'form': form,},
context_instance=RequestContext(request))
def username_is_send(request, template_name='tmp/username.html'):
return render_to_response(template_name, context_instance=RequestContext(request))
Thanks!
Craphunter
You need to store the state somehow in order to pass parameters through a redirect. Multiple possibilities:
Store the mail address in the session, then read in the session variable again in the username_is_send view.
Use a GET parameter to pass the mail address.
And it's "pass", not "path". And the "def" is called (view) function.

Categories

Resources