Python Daily
2.57K subscribers
1.48K photos
53 videos
2 files
38.9K links
Daily Python News
Question, Tips and Tricks, Best Practices on Python Programming Language
Find more reddit channels over at @r_channels
Download Telegram
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
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
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'm too stupid for AsyncIO (x-post from hackernews)
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
# 1
# 2
# 3
# 4
[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
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
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