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
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
Grouping in Django queries

I have a query set object with has two attributes: words, number_of_letters. I would like to group the words by the no of letters in them. For example, all the words with 4 letters should be grouped together. How do I do this when I don't know the maximum number of letters the grouping has? Will I be able to put the grouping into separate objects?

Also, is there a way to modify all the words in the object in one go? For example, if I need to prefix a string to all the words in the object?

/r/django
https://redd.it/691w5b
Django-Haystack, using custom views and forms for filtering



I've got a search view at the moment but would like to create a form to add check box filtering to the search results.

from haystack.generic_views import SearchView
from haystack.query import SearchQuerySet
from haystack.forms import SearchForm


class NoteSearchView(SearchView):

template_name = 'search.html'
form_class = SearchForm

def get_queryset(self):

queryset = SearchQuerySet()
return queryset

I want to create a category filter of 'Sports', 'Fiction', & 'Non-Fiction'. Any thoughts on how to achieve this? I thought maybe I could use the ModelSearchForm but override the default values in some way.

Thank you.


/r/djangolearning
https://redd.it/67vuuk
Computer Freeze running recommender model create

I'm using GraphLab Create with a Jupyter Notebook. This is my first foray into Machine Learning. I have an NVIDIA GTX 770 and 8GB RAM.

My PC was fine up until I called GraphLab Create's [item_similarity_recommender](https://turi.com/products/create/docs/generated/graphlab.recommender.item_similarity_recommender.ItemSimilarityRecommender.html) on ~80M rows of data. Not only did the Notebook freeze but my entire computer did. As soon as I ran the command, it was locking up every half second. I have run the command on smaller (10,000) datasets before with no problem.

How do I solve this issue? Use a Cloud platform?

/r/IPython
https://redd.it/691bn6
[Ask Flask] Moving database from sqlite to postgres causes a 400 Bad Request error

My code is working fine if I use a sqlite database but raises a 400 Bad Request error when I use a postgres database. This error is raised when I query the database. I tried deleting the request arguments from the query and that solves the problem however I want to keep the request arguments. Can you explain what causes flask to raise a 400 error when I use postgres and request arguments and tell me what I can do to solve the problem?

Code with request arguments:

@app.route("/data", methods=["GET"])
def data():
conn = e.connect()
nelat = request.args["neLat"]
nelng = request.args["neLng"]
swlat = request.args["swLat"]
swlng = request.args["swLng"]
query = conn.execute("SELECT * FROM coordinates WHERE lat < ? AND lat > ? AND lng < ? AND lng > ?", [float(nelat), float(nelng), float(swlat), float(swlng)])
result = {'data': [dict(zip(tuple (query.keys()) ,i)) for i in query.cursor]}
jsonData = json.dumps(result)
return jsonData

Code without request arguments:

@app.route("/data", methods=["GET"])
def data():
conn = e.connect()
query = conn.execute("SELECT * FROM coordinates")
result = {'data': [dict(zip(tuple (query.keys()) ,i)) for i in query.cursor]}
jsonData = json.dumps(result)
return jsonData


/r/flask
https://redd.it/694vki
Python equivalent for R Step-wise Regression (direction='Both')

I am trying to find a python version for R's Function(I forget which Library):

step(lm(y~x),direction='both')

In other words, I need a step-wise function that take the best AIC's from both forward and backwards, and return the correlated model (coefficients, p-values,and R value)
Is there one?

/r/pystats
https://redd.it/68pikh