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
Why did Flask run past CherryPy?

I've been wondering this off and on for awhile. I've been a user of
Python before Flask existed and CherryPy served me well then. And it
still does now. I simply don't understand what motivated the creation
of Flask when CherryPy already existed. And I certainly dont
understand why anyone who did a point-for-point comparision of
frameworks before choosing one would choose Flask, save for popularity
of the author.

The first thing I notice about Flask is manual routing whereas
CherryPy has automatic routing by default. That seems like a step
backward not forward.

The rest of my observations about the 2 microframeworks I will post as
a reply
to
[Eric Larsen's post on the subject](http://ionrock.org/2014/12/19/flask_vs_cherrypy.html).

> I suspect the reason CherryPy is not seen a hip framework is due to
> most users of CherryPy happily work around the rough edges and get
> work done rather than make an effort market their framework of
> choice.

I agree that CherryPy is not popular. I dont know what rough edges you
are taking about. It works fine for me.

> The best thing I can say about Flask is the community of projects.

Seconded. There are a lot of downloadable flask apps and plugins.

> Flask-Admin is extremely helpful along side Flask-SQLAlchemy.

Yes, I really like an automatic admin interface. That is the one thing
I miss from Django. And what I disliked about Django (`settings.py`)
is solved by something called `importd` (but I cant find a link to
it). But what I see as unsolveable by Django is that the ORM is not SQLAlchemy and I refuse to have things like "Stale MySQL handle" errors... anyway, back to the CherryPy/Flask topic of this post.

> Unfortunately, while this wealth of excellent community packages is
> excellent, Flask falls short when it comes to actual
> development. Its lack of organization in terms of dispatching makes
> organizing code feel very haphazard. It is easy to create circular
> dependencies due to the use of imports for establishing what code
> gets called. In essence, Flask forces you to build some patterns
> that are application specific rather than prescribing some models
> that make sense generally.

> While a lack of direction can make the organization of the code less
> obvious, it does allow you to easily hook applications together. The
> Blueprint model, from what I can tell, makes it reasonably easy to
> compose applications within a site.

Hmm, being able to mount applications is a big thing and if Flask
forces you through a tube to do it, then that sounds like an OK
thing.


/r/Python
https://redd.it/68ff8b
How do I make my package available to do 'conda install XXXX'? I already got 'conda install -c jos_pol pandas-profiling' working

Hi all,

Does anybody know how to register a package in the main Anaconda channels? I already got

> conda install -c jos_pol pandas-profiling

working. Ideally, i would like to have instead

> conda install pandas-profiling

Just like with pip you just have

>pip install pandas-profiling

Is that even possible or is it restricted to a manually curated list by the Anaconda folks?

/r/pystats
https://redd.it/68eojb
Why use RESTfull API?

So far I just worked with flask rendering all websites itself. Example: http://flask.pocoo.org/
Yesterday I heard about RESTfull API. Example: https://blog.miguelgrinberg.com/post/designing-a-restful-api-with-python-and-flask
What is the advantage of separating the front end (VueJS, AngularJS, ...) and the backend (flask, returning JSON)? Unfortunately, I didn't understand the reason.

/r/flask
https://redd.it/68dwz4
Google assistant on MacOS

I got the google assistant to launch on macOS with one touch

I had to modify the python code samples slightly to exit when a conversation is complete. Used automator to create an app out of shell script that activates virtualenv and runs the code.
Finally, I am using better touch tool to launch the app with a corner-tap on the trackpad.

Best part is that it recognizes my accent perfectly :)

Demo: [YouTube] (https://www.youtube.com/watch?v=WJ-6TR2p9S8)


/r/Python
https://redd.it/68koid
[New to Django & Python] Is the two scoops book good for learning Django as a beginner who doesn't have experience with frameworks?

I o a do-able tutorial from the djangobook.com site - title, but it's outdated and i already have Django 1.11 installed. It's like solving a puzzle now instead of following the tutorial/guide. I have to search on the web for the out-dated answers and i am thinking about reading the two scoops book but will it be to hard, isn't it just a reference book which expects you to be experienced already with Django?

/r/django
https://redd.it/68ls3d
Problems using Flask and AngularJS together

Im making a simple web applciation right now using Flask and AngularJS. However, since adding some AngularJS code to my web page, im having problems running my website locally. I just keep getting errors saying things in my Angular code are not defined [like this](http://imgur.com/a/zvkRH) when they run perfectly when i just double click on the .html file without starting up my flask app.

My code is [here if](https://pastebin.com/e0aGnBCN) for you to take a look at if needed.

Is there something I should be doing to make them work together or are they not compatible or something?

/r/flask
https://redd.it/68mhnc
Using Django/DRF view logic in Channels consumers

I have a django/Django REST framework instant message application working with HTTP requests. I'm trying to implement realtime websocket messaging, but I'm unsure of how to structure the code. I have some spaghetti code written and I can bounce a message I send from the client to the server and issue a socket response, but I have business logic from my POST /messages view that I think needs to be included in the consumers.py file.

I'm using a generics.ListCreateAPIView to POST to my messages endpoint and using the Google translate API to translate it to multiple languages that all get stored to the DB.

Current routing.py:

channel_routing = [
route("websocket.connect", consumers.ws_connect),
route("websocket.receive", consumers.ws_receive),
]
consumers.py:

@channel_session_user_from_http
def ws_connect(message):
message.reply_channel.send({"accept": True})
prefix, chat_id = message['path'].strip('/').split('/')
chat = Chat.objects.get(id=chat_id)
Group('chat-' + chat_id).add(message.reply_channel)
message.channel_session['chat'] = chat.id

@channel_session_user
def ws_receive(message):
chat_id = message.channel_session['chat']
chat = Chat.objects.get(id=chat_id)
data = message['text']
m = chat.messages.last()
Group('chat-'+str(chat_id)).send({'text': json.dumps(model_to_dict(m))})

I'm wondering if I can send the socket payload to my message creation view and then send the resulting validated/saved serializer to the rest of the connected clients.

/r/django
https://redd.it/68p5in
[D] GANs for text generation: progress in the last year?

I am looking to conditionally generate relatively short, relatively structured texts. Specifically, I'm trying to generate plausible recipes given a subset of required ingredients, like "make me something with beef and potatoes". Ultimately I'm interested in seeing if it's possible to generate plausible recipes from ingredient combinations that aren't in the database.

I had initially thought of using a conditional RNN-GAN for this, with a fixed-length (for now) list of GloVe-embedded required ingredients provided as context. Then I found an obvious-in-hindsight post from /u/goodfellow_ian/ from a year ago explaining why that wouldn't work: https://www.reddit.com/r/MachineLearning/comments/40ldq6/generative_adversarial_networks_for_text/

Put (over-)simply: GANs are near-impossible to train in discrete output domains as the generator cannot smoothly improve. I'm fairly inexperienced at recurrent approaches, but that raises two questions for me:

1) has any progress been made since that post was written on applying adversarial training to text or other discrete domains?

and 2) Why wouldn't it work if I trained a GAN to output a non-recurrent continuous intermediary representation? Something like the hidden layer of a recurrent autoencoder (trained on the database of real recipes, then frozen)? This seems obvious, and I'm not an expert, so my immediate assumption is that it would fail spectacularly for some reason I have not yet grasped. So I thought I'd ask you folks before I tried it!

/r/MachineLearning
https://redd.it/68lyuu
First internship, using Django

Just started my first internship and the project I will be working on uses Django framework. I've previously done the Django polls tutorial as well as the djangogirls blog tutorial. However both of these barely touched testing (which is what I will be doing during my first weeks).

Any suggestions on how to understand full blown django projects since the codebase for the project is quite large and uses all kinds of plugins. Not sure if I should just try to learn everything at work or take some time to read up on my own. As far as tests go, the ones in place right now are pretty complex so I'm looking for any help. Theres only one other developer at the company that I know of and he is not always available

/r/django
https://redd.it/68p2nx
Why Nginx/Gunicorn/Flask?

I've successfully setup this stack a couple times now and have seen it done in professional settings so the only reason is basically "monkey see monkey do". When googling to figure it out, I've only been able to find the how and not the why... Why the heck is this stack so popular? What are the reasons it is effective? Why not simply run a Flask server that takes requests straight from port 80 instead of the reverse proxy?

/r/Python
https://redd.it/68phcu
Struggling with file validation

I've been trying to get some audio file validation going with my project (for user uploads), finally found this python package 'django-constrainedfilefield 3.0.3'. For some reason, I can't get my forms to work. when I hit the submit on the form, it never triggers the redirect or a validation error, just reloads the form. Here is my model
class Places(models.Model):

title= models.CharField(max_length=100)
sound= ConstrainedFileField(max_upload_size= 4294967296
, content_types = ['audio/mpeg','audio/mp4','audio/ogg',])
rating= GenericRelation(Rating, related_query_name='foos')
usersave= models.CharField(max_length=100)

my view
def post_create(request):
form= PostForm(request.POST or None, request.FILES or None)


if form.is_valid():

instance = form.save(commit=False)
instance.save()
messages.success(request, 'Successfully Created')
return HttpResponseRedirect('/')


context= {
'form': form,
}
return render(request, 'location/post_form.html',context,)

and my form:

class PostForm(forms.ModelForm):



class Meta:
model = Places
fields = [


'title',
'sound',

]
I'm a bit confused about how django-constrainedfilefield actually works, it doesn't raise any validation errors and doesn't allow me to actually submit the form even if the filetype is correct, which makes me think I'm missing something? Any help would be MUCH appreciated I've been working on this problem for days



/r/django
https://redd.it/68qxxm
ELI5 File and BytesIO

I've found that an image downloaded by using `requests` must be made into a `File` before Pillow will accept it.

On the other hand, an image `File` must be saved to a `BytesIO` and seeked to 0 so it can be used with `Popen`, for example with mozjpeg.

How do I know which to use where, besides trial-and-error?

I have a similar issue with text, where through trial and error I found that I need `encode()` before `hmac` is used, then `decode()` for final output.

/r/Python
https://redd.it/68rx39
How to run a script against a Class.object?

I've created an app that displays several websites, my models.py has a class with: website_name, and website_address.

What I would like to do is run:
requests.get(website_address).status_code

So that a status code will display but I am unsure if I run the requests within views or within models? I would like for it to update at least every 60 seconds via the index.html:
<meta http-equiv="refresh" content="60" />

The class with website_name/address within the admin is great because I can change out different sites for monitoring purposes as different days has me monitoring different sites.

Any suggestions would be greatly appreciated

/r/djangolearning
https://redd.it/68qw23
Conditional field validation

Trying to conditionally validate my database model that holds external identity information (i.e. Reddit or Discord). I ended up going with this, but was wondering if there's a native way of doing it.

class ExternalContact(Timestampable, models.Model):
class Types(ChoiceEnum):
REDDIT = 'Reddit'
DISCORD = 'Discord'

validators = {
Types.REDDIT.value: [
RegexValidator(r"\A[\w-]+\Z"),
MinLengthValidator(3),
MaxLengthValidator(20),
],
Types.DISCORD.value: [
RegexValidator(r"\A[^@#]+#[0-9]{4}\z"),
MinLengthValidator(7), # min 2 chars + 5 profile chars (i.e. #1234)
MaxLengthValidator(37), # max 32 chars + 5 profile chars (i.e. #1234)
]
}

username = models.CharField(max_length=128)
type = models.CharField(max_length=128, choices=Types.choices(), default=Types.REDDIT)

def clean(self):
errors = list()
for validator in self.validators[self.type]:
try:
validator(self.username)
except ValidationError as e:
errors.append(e)
if errors:
raise ValidationError(errors)

def __str__(self):
return self.username

class Meta:
verbose_name_plural = "External Contacts"
unique_together = (("username", "type"),)

/r/djangolearning
https://redd.it/68il59