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
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
Google Assistant Support for PC with VoiceAttack and python

https://puu.sh/vDODX/72f32e65db.png

~~How they do it~~**EDIT:** Quick Rundown:
Following this [tut](https://www.xda-developers.com/how-to-get-google-assistant-on-your-windows-mac-or-linux-machine/) i enabled google assistant for pc, but i found it to be lacking. For one it lacked the most basic feature: voice activation. Immediately i thought of the program Voiceattack. but the problem was hooking into it with python, which the assistant api is built on.

I took this [script](https://github.com/googlesamples/assistant-sdk-python/blob/master/googlesamples/assistant/__main__.py) from the assistant sdk and modified it like [so](https://github.com/Azimoto9/assistant-custom/blob/master/googlesamples/assistant/__main__.py)

Next I added a little cmd command to the mix:

py -c "from distutils.sysconfig import get_python_lib; from urllib.request import urlretrieve; urlretrieve('file:///C:/Users/austin/Downloads/assistant-sdk-python-master/googlesamples/assistant/__main__.py', get_python_lib() + '/googlesamples/assistant/__main__.py')"
(you can use this, substituting it with your own paths)

and then i set up voice attack. using some simple batch files i had voice attack open and close python/cmd/conhost
I had previously had the python script run a keystroke: ctrl-shift-alt-L, to hook into voice attack, this ran a command that closed the aforementioned processes.

Finally I had it working, with some tweaks to the timing so that it never misfired, it was ready to go. and it works pretty good, albeit it is a little ghetto and could use a lot of simplification/refining. perhaps someone could use what i did and create a better application with its own voice recognition/hotword detection and even a GUI?

TLDR: did some python magic and used nonfree software to create better google assistant support, maybe someone could improve upon what i did.


/r/Python
https://redd.it/68y8lv
[R] Deep Image Analogy

/r/MachineLearning
https://redd.it/68y8bb
Problem with saleor. Category page not loading after running npm start and yarn run build-assets

After running yarn run build-assets so that I can change the css, I can't see any of the categories' loading the items in the page. Before running it I could see the category items.
I am using ngx_pagespeed. Could that be the cause the problems I am having? The js in all the other pages is working properly except for categories.

/r/django
https://redd.it/68zpya