What's the best way to redirect to a different view in the case of an exception?
Hi there,
I'm implementing a payment system on my site and I'm wondering what the best practice way to handle exceptions would be. The exception handling for CC processing is built into the payment processor (Stripe), so that part's not a problem. What I'm trying to determine is what's the best way for me to handle an exception if one is caught, for example a card processing error (e.g. credit card was declined).
In the view that processes the card, it takes a token returned by Stripe, tries to create a customer, assign them to a subscription, and if it fails there are a number of exceptions thrown like CardError, AuthenticationError, InvalidRequestError, etc. In those exceptions I am able to trap the error message easily (e.g. "your credit card was declined") and then return a different template, like subscribe_error.html, which can show the error as a template variable. No problem. The only problem there is that the URL still shows the thank you URL. So I really need to redirect to the error url (e.g. /subscribeerror or whatever), but keep the error message. So what's the best practice way to do this?
Basically, the error handling works, but I just don't know if I am doing it the best way I can. Here's some code:
def pro_annual_thanks(request):
token = request.POST.get('stripeToken')
email = request.POST.get('stripeEmail')
name = request.POST.get('stripeName')
customer_data = {
'description': name,
'card': token,
'email': email
}
try:
stripe.api_key = settings.STRIPE_TEST_SECRET_KEY
customer = stripe.Customer.create(**customer_data)
subscription = customer.subscriptions.create(plan="annual_pro")
except stripe.error.CardError as e:
# Since it's a decline, stripe.error.CardError will be caught
body = e.json_body
err = body.get('error', {})
print "Status is: %s" % e.http_status
print "Type is: %s" % err.get('type')
print "Code is: %s" % err.get('code')
# param is '' in this case
print "Param is: %s" % err.get('param')
print "Message is: %s" % err.get('message')
### SHOULD I REDIRECT HERE INSTEAD? ###
### HOW DO I KEEP THE ERROR MESSAGE? ###
### I HAVE A URL FOR SUBSCRIBE ERRORS IF NEEDED ###
### AND ALSO A subscribe_error(request, error) VIEW ###
template = 'subscribe_error.html'
context = {
'error' : err.get('message')
}
return render(request, template, context)
context = {
'plan' : 'Annual Pro',
'custName' : name,
'custEmail' : email
}
template = 'pro_annual_thanks.html'
return render(request, template, context)
I know a few different ways to do this, for example I could store the context in the session and then pull it from the subscribe_error() view. I could also use redirect() or HttpResponseRedirect() but I'm not sure which, or what the best practice would be.
Any tips? Thanks!
/r/django
https://redd.it/6xxoeo
Hi there,
I'm implementing a payment system on my site and I'm wondering what the best practice way to handle exceptions would be. The exception handling for CC processing is built into the payment processor (Stripe), so that part's not a problem. What I'm trying to determine is what's the best way for me to handle an exception if one is caught, for example a card processing error (e.g. credit card was declined).
In the view that processes the card, it takes a token returned by Stripe, tries to create a customer, assign them to a subscription, and if it fails there are a number of exceptions thrown like CardError, AuthenticationError, InvalidRequestError, etc. In those exceptions I am able to trap the error message easily (e.g. "your credit card was declined") and then return a different template, like subscribe_error.html, which can show the error as a template variable. No problem. The only problem there is that the URL still shows the thank you URL. So I really need to redirect to the error url (e.g. /subscribeerror or whatever), but keep the error message. So what's the best practice way to do this?
Basically, the error handling works, but I just don't know if I am doing it the best way I can. Here's some code:
def pro_annual_thanks(request):
token = request.POST.get('stripeToken')
email = request.POST.get('stripeEmail')
name = request.POST.get('stripeName')
customer_data = {
'description': name,
'card': token,
'email': email
}
try:
stripe.api_key = settings.STRIPE_TEST_SECRET_KEY
customer = stripe.Customer.create(**customer_data)
subscription = customer.subscriptions.create(plan="annual_pro")
except stripe.error.CardError as e:
# Since it's a decline, stripe.error.CardError will be caught
body = e.json_body
err = body.get('error', {})
print "Status is: %s" % e.http_status
print "Type is: %s" % err.get('type')
print "Code is: %s" % err.get('code')
# param is '' in this case
print "Param is: %s" % err.get('param')
print "Message is: %s" % err.get('message')
### SHOULD I REDIRECT HERE INSTEAD? ###
### HOW DO I KEEP THE ERROR MESSAGE? ###
### I HAVE A URL FOR SUBSCRIBE ERRORS IF NEEDED ###
### AND ALSO A subscribe_error(request, error) VIEW ###
template = 'subscribe_error.html'
context = {
'error' : err.get('message')
}
return render(request, template, context)
context = {
'plan' : 'Annual Pro',
'custName' : name,
'custEmail' : email
}
template = 'pro_annual_thanks.html'
return render(request, template, context)
I know a few different ways to do this, for example I could store the context in the session and then pull it from the subscribe_error() view. I could also use redirect() or HttpResponseRedirect() but I'm not sure which, or what the best practice would be.
Any tips? Thanks!
/r/django
https://redd.it/6xxoeo
reddit
What's the best way to redirect to a different view in... • r/django
Hi there, I'm implementing a payment system on my site and I'm wondering what the best practice way to handle exceptions would be. The exception...
[D] My Neural Network isn't working! What should I do? - A list of common mistakes made by newcomers to neural networks.
http://theorangeduck.com/page/neural-network-not-working
/r/MachineLearning
https://redd.it/6xvnwo
http://theorangeduck.com/page/neural-network-not-working
/r/MachineLearning
https://redd.it/6xvnwo
Theorangeduck
My Neural Network isn't working! What should I do?
Computer Science, Machine Learning, Programming, Art, Mathematics, Philosophy, and Short Fiction
Django's cache clear function does not work on view cache?
I am using the view cache for Django 1.10. But I am having problems clearing the cache.
@cache_page(60 * 30, cache="container_table")
def container_table(request, dataset):
# determine container_list by a query to the database
return render(request, 'container_table.html',{"container_list":container_list})
Then container_table.html creates a table involving container_list and each row has an element of container_list along with a little checkbox. When the checkbox is checked, I want the cache to clear. So essentially when the checkbox is checked, an ajax call is made to a view that does caches["container_table"].clear(). From the django docs, this should clear ALL keys in that cache, but it is not working because when I refresh the page for container_table.html it is still using a cache. Am I misunderstanding the usage of caches["container_table"].clear()? I thought it would clear everything!
/r/django
https://redd.it/6xv7a5
I am using the view cache for Django 1.10. But I am having problems clearing the cache.
@cache_page(60 * 30, cache="container_table")
def container_table(request, dataset):
# determine container_list by a query to the database
return render(request, 'container_table.html',{"container_list":container_list})
Then container_table.html creates a table involving container_list and each row has an element of container_list along with a little checkbox. When the checkbox is checked, I want the cache to clear. So essentially when the checkbox is checked, an ajax call is made to a view that does caches["container_table"].clear(). From the django docs, this should clear ALL keys in that cache, but it is not working because when I refresh the page for container_table.html it is still using a cache. Am I misunderstanding the usage of caches["container_table"].clear()? I thought it would clear everything!
/r/django
https://redd.it/6xv7a5
reddit
Django's cache clear function does not work on view cache? • r/django
I am using the view cache for Django 1.10. But I am having problems clearing the cache. @cache_page(60 * 30, cache="container_table") def...
Universities finally realize that Java is a bad introductory programming language
https://thenextweb.com/dd/2017/04/24/universities-finally-realize-java-bad-introductory-programming-language/#.tnw_PLAz3rbJ
/r/Python
https://redd.it/6xy6ld
https://thenextweb.com/dd/2017/04/24/universities-finally-realize-java-bad-introductory-programming-language/#.tnw_PLAz3rbJ
/r/Python
https://redd.it/6xy6ld
The Next Web
Universities finally realize that Java is a bad introductory programming language
What's this "public static void" crap?
Trouble with def+vuejs+axios (Can't set auth paramerters/headers).
I am using axios with vue to get/post data from my local api using DRF. The get requests seem to be working fine(since they don't need authentication) but having trouble with post requests(require basic auth).
I have configured for cors requests using django-cors-headers package as follows (cors package is added to apps, middelware properly):
CORS_ORIGIN_ALLOW_ALL = True
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
The error I am getting is 403 Forbidden(authentication credentials were not provided).
[Network tab of chrome](http://imgur.com/a/aK74s)
[Vue file](https://gist.github.com/Attila03/3398c4a3c55a9812211274d2cb61b761)
Also, sending similar requests from Postman client seems to be working fine.
/r/django
https://redd.it/6xzdbw
I am using axios with vue to get/post data from my local api using DRF. The get requests seem to be working fine(since they don't need authentication) but having trouble with post requests(require basic auth).
I have configured for cors requests using django-cors-headers package as follows (cors package is added to apps, middelware properly):
CORS_ORIGIN_ALLOW_ALL = True
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
The error I am getting is 403 Forbidden(authentication credentials were not provided).
[Network tab of chrome](http://imgur.com/a/aK74s)
[Vue file](https://gist.github.com/Attila03/3398c4a3c55a9812211274d2cb61b761)
Also, sending similar requests from Postman client seems to be working fine.
/r/django
https://redd.it/6xzdbw
Imgur
Imgur: The most awesome images on the Internet
Imgur: The most awesome images on the Internet.
I'm too stupid for AsyncIO (x-post from hackernews)
https://whatisjasongoldstein.com/writing/im-too-stupid-for-asyncio/
/r/Python
https://redd.it/6xxy2q
https://whatisjasongoldstein.com/writing/im-too-stupid-for-asyncio/
/r/Python
https://redd.it/6xxy2q
Do you even log? Questions about your logging habbits considering web apps...
Hey Flask Users,
I am interested in what you are logging in your web apps.
E.g.
+ User activities
+ Http Headers
+ Authentications
+ Errors/Warnings
+ ...
How do you log these things:
+ In a database
+ Files
+ Mails
+ Do you summarize your logs automatically?
And which technology/place you use:
+ Flask
+ Webserver
+ Frontend/js
At the moment I am just logging Python and Flask errors and warnings in a text file using Flask. Additionaly I use the standard logs of Apache Webserver (basic information about single requests and web server errors). But as I am planning to make one of my apps public I probably increase and improve my logging habbits to ensure a stable and safe service for my users...
/r/flask
https://redd.it/6xyxyk
Hey Flask Users,
I am interested in what you are logging in your web apps.
E.g.
+ User activities
+ Http Headers
+ Authentications
+ Errors/Warnings
+ ...
How do you log these things:
+ In a database
+ Files
+ Mails
+ Do you summarize your logs automatically?
And which technology/place you use:
+ Flask
+ Webserver
+ Frontend/js
At the moment I am just logging Python and Flask errors and warnings in a text file using Flask. Additionaly I use the standard logs of Apache Webserver (basic information about single requests and web server errors). But as I am planning to make one of my apps public I probably increase and improve my logging habbits to ensure a stable and safe service for my users...
/r/flask
https://redd.it/6xyxyk
reddit
Do you even log? Questions about your logging habbits... • r/flask
Hey Flask Users, I am interested in what you are logging in your web apps. E.g. + User activities + Http Headers + Authentications +...
mypy infrastructure PR has been merged into pip
https://github.com/pypa/pip/pull/4545
/r/Python
https://redd.it/6y02tj
https://github.com/pypa/pip/pull/4545
/r/Python
https://redd.it/6y02tj
GitHub
Add infrastructure support for static type-checking using mypy by pradyunsg · Pull Request #4545 · pypa/pip
mypy type-checking would be a useful addition.
Ref: #4021
Quick summary of the changes in the PR (as on 2nd Sept 2017):
Add a new CI job that runs mypy checks
Add .pyi stubs for the vendored modu...
Ref: #4021
Quick summary of the changes in the PR (as on 2nd Sept 2017):
Add a new CI job that runs mypy checks
Add .pyi stubs for the vendored modu...
Spiral Barcode Generator: Rick and Morty Episode 101
https://imgur.com/a/nYeDB
/r/Python
https://redd.it/6y56v3
https://imgur.com/a/nYeDB
/r/Python
https://redd.it/6y56v3
Imgur
Rick and Morty Story Circle and Barcodes for episode 101
Imgur: The most awesome images on the Internet.
Announcing Kernels, a Jupyter Notebook client for iPad (x-post from /r/MachineLearning)
https://www.reddit.com/r/MachineLearning/comments/6y0ur3/announcing_kernels_a_jupyter_notebook_client_for/
/r/IPython
https://redd.it/6y0vsd
https://www.reddit.com/r/MachineLearning/comments/6y0ur3/announcing_kernels_a_jupyter_notebook_client_for/
/r/IPython
https://redd.it/6y0vsd
reddit
Announcing Kernels, a Jupyter Notebook client... • r/MachineLearning
reddit: the front page of the internet
Hatch - A modern project, package, and virtual env manager
https://github.com/ofek/hatch
/r/Python
https://redd.it/6y69iw
https://github.com/ofek/hatch
/r/Python
https://redd.it/6y69iw
GitHub
GitHub - pypa/hatch: Modern, extensible Python project management
Modern, extensible Python project management. Contribute to pypa/hatch development by creating an account on GitHub.
[AF] Help with combining two Flask-SqlAlchemy queries into one
I have looked myself blind on this issue. Is anybody familiar with SqlAlchemy and can help me in the right direction with combining the following two queries into one query, giving a total count?
unread_count1 = models.MessageThread.query.join(models.AppReg, models.MessageThread.source_app)\
.filter(and_(models.MessageThread.source_read == 0, models.MessageThread.source_archived == 0))\
.filter(models.AppReg.user_UID == g._user.uid)\
.count()
unread_count2 = models.MessageThread.query.join(models.AppReg, models.MessageThread.target_app)\
.filter(and_(models.MessageThread.target_read == 0, models.MessageThread.target_archived == 0))\
.filter(models.AppReg.user_UID == g._user.uid)\
.count()
/r/flask
https://redd.it/6y3agr
I have looked myself blind on this issue. Is anybody familiar with SqlAlchemy and can help me in the right direction with combining the following two queries into one query, giving a total count?
unread_count1 = models.MessageThread.query.join(models.AppReg, models.MessageThread.source_app)\
.filter(and_(models.MessageThread.source_read == 0, models.MessageThread.source_archived == 0))\
.filter(models.AppReg.user_UID == g._user.uid)\
.count()
unread_count2 = models.MessageThread.query.join(models.AppReg, models.MessageThread.target_app)\
.filter(and_(models.MessageThread.target_read == 0, models.MessageThread.target_archived == 0))\
.filter(models.AppReg.user_UID == g._user.uid)\
.count()
/r/flask
https://redd.it/6y3agr
reddit
[AF] Help with combining two Flask-SqlAlchemy queries... • r/flask
I have looked myself blind on this issue. Is anybody familiar with SqlAlchemy and can help me in the right direction with combining the following...
Best way to do dynamic models? (or any other solution?)
Hi all,
I want to implement the following:
A "document" is a collection of different "components" that can be just about anything (text, images, dates, links, output of custom scripts, whatever).
Each component can get status (draft, validated, disabled..), comments, history, validation etc.
We only know at runtime what kind of components a specific document will have, and how many.
I'm a bit lost on how to even get started. I saw some things about dynamic forms, but I can't really get how to relate this with a model.
Any suggestions on how to achieve that using Django? Or maybe it's not the right framework for what I want?
Thanks a lot!
/r/django
https://redd.it/6y78ih
Hi all,
I want to implement the following:
A "document" is a collection of different "components" that can be just about anything (text, images, dates, links, output of custom scripts, whatever).
Each component can get status (draft, validated, disabled..), comments, history, validation etc.
We only know at runtime what kind of components a specific document will have, and how many.
I'm a bit lost on how to even get started. I saw some things about dynamic forms, but I can't really get how to relate this with a model.
Any suggestions on how to achieve that using Django? Or maybe it's not the right framework for what I want?
Thanks a lot!
/r/django
https://redd.it/6y78ih
reddit
Best way to do dynamic models? (or any other solution?) • r/django
Hi all, I want to implement the following: A "document" is a collection of different "components" that can be just about anything (text,...
What's everyone working on this week?
Tell /r/python what you're working on this week! You can be bragging, grousing, sharing your passion, or explaining your pain. Talk about your current project or your pet project; whatever you want to share.
/r/Python
https://redd.it/6y87sb
Tell /r/python what you're working on this week! You can be bragging, grousing, sharing your passion, or explaining your pain. Talk about your current project or your pet project; whatever you want to share.
/r/Python
https://redd.it/6y87sb
reddit
What's everyone working on this week? • r/Python
Tell /r/python what you're working on this week! You can be bragging, grousing, sharing your passion, or explaining your pain. Talk about your...
Raspberry Pie: A discord guild with over 1,800 users where you can get help with your code from a moderately active community
https://discord.gg/P6zsmZm
/r/Python
https://redd.it/6y84d7
https://discord.gg/P6zsmZm
/r/Python
https://redd.it/6y84d7
Discord
Discord - Free voice and text chat for gamers
Step up your game with a modern voice & text chat app. Crystal clear voice, multiple server and channel support, mobile apps, and more. Get your free server now!
Django security releases issued: 1.11.5 and 1.10.8
https://www.djangoproject.com/weblog/2017/sep/05/security-releases/
/r/django
https://redd.it/6y9iy1
https://www.djangoproject.com/weblog/2017/sep/05/security-releases/
/r/django
https://redd.it/6y9iy1
reddit
Django security releases issued: 1.11.5 and 1.10.8 • r/django
5 points and 0 comments so far on reddit