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
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
reddit
Conditional field validation • r/djangolearning
Trying to conditionally validate my database model that holds external identity information (i.e. Reddit or Discord). I ended up going with this,...
All in one library for Notifications (SMS, PUSH, EMAIL)
https://github.com/inforian/django-notifyAll
/r/Python
https://redd.it/68sj0e
https://github.com/inforian/django-notifyAll
/r/Python
https://redd.it/68sj0e
GitHub
inforian/django-notifyAll
django-notifyAll - A library which can be used for all types of notifications like SMS, Mail, Push.
A Beginner's Guide to Neural Networks in Python and SciKit Learn 0.18
https://www.springboard.com/blog/beginners-guide-neural-network-in-python-scikit-learn-0-18/
/r/Python
https://redd.it/68uhx9
https://www.springboard.com/blog/beginners-guide-neural-network-in-python-scikit-learn-0-18/
/r/Python
https://redd.it/68uhx9
Springboard Blog
A Beginner’s Guide to Neural Networks in Python
Understand how to implement a neural network in Python with this code example-filled tutorial.
Inheritance versus Composition in Python - Designing Modules Part - 5
https://hashedin.com/2017/01/03/inheritance-versus-composition/
/r/Python
https://redd.it/68yqy5
https://hashedin.com/2017/01/03/inheritance-versus-composition/
/r/Python
https://redd.it/68yqy5
HashedIn
Inheritance versus Composition in Python - Designing Modules Part - 5
Part 5 of designing modules compares inheritance versus composition, and shows how new business requirements can be added without changing existing code.
Start a flask project from zero: Building an REST API
https://tutorials.technology/tutorials/59-Start-a-flask-project-from-zero-building-api-rest.html
/r/flask
https://redd.it/68vtib
https://tutorials.technology/tutorials/59-Start-a-flask-project-from-zero-building-api-rest.html
/r/flask
https://redd.it/68vtib
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
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
Get Started with PySpark and Jupyter Notebook in 3 Minutes
https://medium.com/@charlesb_55383/get-started-pyspark-jupyter-guide-tutorial-ae2fe84f594f
/r/Python
https://redd.it/690mcw
https://medium.com/@charlesb_55383/get-started-pyspark-jupyter-guide-tutorial-ae2fe84f594f
/r/Python
https://redd.it/690mcw
Medium
Get Started with PySpark and Jupyter Notebook in 3 Minutes
Apache Spark is a must for Big data’s lovers. In a few words, Spark is a fast and powerful framework that provides an API to perform…
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
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
reddit
Problem with saleor. Category page not loading after... • r/django
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...
socketserver: the networking module you didn't know you needed
http://silverwingedseraph.net/programming/2016/12/23/socketserver-the-python-networking-module-you-didnt-know-you-needed.html
/r/Python
https://redd.it/690zoz
http://silverwingedseraph.net/programming/2016/12/23/socketserver-the-python-networking-module-you-didnt-know-you-needed.html
/r/Python
https://redd.it/690zoz
Silver Winged Statements
socketserver: the Python networking module you didn't know you needed
Leo Tindall's blog about code and computers.
REST APIs with Flask and Python
https://medium.com/@RobSm/rest-apis-with-flask-and-python-db8b4f6cc433
/r/flask
https://redd.it/6905v7
https://medium.com/@RobSm/rest-apis-with-flask-and-python-db8b4f6cc433
/r/flask
https://redd.it/6905v7
Medium
REST APIs with Flask and Python
Are you tired of boring, outdated, incomplete, or incorrect tutorials? I say no more to copy-pasting code that you don’t understand.
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
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
reddit
Grouping in Django queries • r/django
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...
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
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
reddit
Django-Haystack, using custom views and forms... • r/djangolearning
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...
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
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
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
reddit
[Ask Flask] Moving database from sqlite to postgres... • r/flask
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...
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
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
reddit
Python equivalent for R Step-wise Regression... • r/pystats
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...
Help understanding flask sessions
I'm working on a flask app, and so far I haven't added any extensions, but eventually I want to have it employ a workflow something like the following
1) user visits the webapp
2) user uploads some text
3) the upload occurs over a web socket, using flask-socketio, which will then stay open long enough to deliver some analysis of the text
My question is this, what do I have to do to support multiple people accessing the site and using this workflow concurrently? Is it in the sockets, is it in user sessions, do I need to add user accounts? It's just not clear to me how my app should most easily know "this is a new text analysis run, separate from other users' runs that may be occurring."
Also, if anyone can recommend the ideal server for this setup, that would be most appreciated. I know flask-socketio has recommendations, but I don't know how to choose one.
FYI I'm using python 2.7.12 and flask 0.10.1.
Thank you anyone who can help!!!
/r/flask
https://redd.it/693p4k
I'm working on a flask app, and so far I haven't added any extensions, but eventually I want to have it employ a workflow something like the following
1) user visits the webapp
2) user uploads some text
3) the upload occurs over a web socket, using flask-socketio, which will then stay open long enough to deliver some analysis of the text
My question is this, what do I have to do to support multiple people accessing the site and using this workflow concurrently? Is it in the sockets, is it in user sessions, do I need to add user accounts? It's just not clear to me how my app should most easily know "this is a new text analysis run, separate from other users' runs that may be occurring."
Also, if anyone can recommend the ideal server for this setup, that would be most appreciated. I know flask-socketio has recommendations, but I don't know how to choose one.
FYI I'm using python 2.7.12 and flask 0.10.1.
Thank you anyone who can help!!!
/r/flask
https://redd.it/693p4k
reddit
Help understanding flask sessions • r/flask
I'm working on a flask app, and so far I haven't added any extensions, but eventually I want to have it employ a workflow something like the...
[AF] Which cache mechanism are you using?
Hi
I'm currently working on a rather big flask app and was wondering which cache mechanism you are using out there?
Are there many using flask-caching with redis/memcached or is there anything else recommended?
Thank you in advance
/r/flask
https://redd.it/68w7wj
Hi
I'm currently working on a rather big flask app and was wondering which cache mechanism you are using out there?
Are there many using flask-caching with redis/memcached or is there anything else recommended?
Thank you in advance
/r/flask
https://redd.it/68w7wj
reddit
[AF] Which cache mechanism are you using? • r/flask
Hi I'm currently working on a rather big flask app and was wondering which cache mechanism you are using out there? Are there many using...
Postgres Full-Text Search With Django
http://blog.lotech.org/postgres-full-text-search-with-django.html
/r/django
https://redd.it/6940gl
http://blog.lotech.org/postgres-full-text-search-with-django.html
/r/django
https://redd.it/6940gl
Lotechnica
Postgres Full-Text Search With Django
Django has added support for Postgres's built-in full-text searching as of version 1.10. This is a great alternative to a heavier search system such as elasticsearch or SOLR, when we want decent search capabilities without having to setup and maintain another…
Are there best practices for organizing methods between related models?
Hi everyone, I have been working with Django for a while and I really dig it. However I often feel I overcomplicate my code and get lost at determining where everthing is.
For example - one issue I am facing, and am hoping for some insight on, is the following.
I have an application that has Missions (a series of tasks) which get assigned to Members.
A simplified version of the code is
class Mission
title = Charfield
description = Textfield
class MemberMission
mission = Foreignkey to Mission
member = Foreignkey to Member (which is connected to User)
status = Charfield
custom_variables = Dictionaryfield. (holds other data about what they have done or not)
I just realized that I may want the mission description to depend on membermisson variables (eg. perhaps we give more time or less time or vary the reward based on these variables).
So, in the template, rather than showing the field mission.description, I should show a function (get_description) that pulls the description and modifies it based on the membermission data.
My question is this, where would a Django pro put this function?
Should it be on the Membermission
Eg) membermission.get_description()
Or should it be on the Mission
Eg) misson.get_description(membermission)
Or should I have it as a seperate function in some toolbox file (and put it into a template tag)
Eg) toolbox.get_description(membermission)
Or should I just find a source for Adderall and get over all this?
Thank you so much everyone.
/r/django
https://redd.it/696rdp
Hi everyone, I have been working with Django for a while and I really dig it. However I often feel I overcomplicate my code and get lost at determining where everthing is.
For example - one issue I am facing, and am hoping for some insight on, is the following.
I have an application that has Missions (a series of tasks) which get assigned to Members.
A simplified version of the code is
class Mission
title = Charfield
description = Textfield
class MemberMission
mission = Foreignkey to Mission
member = Foreignkey to Member (which is connected to User)
status = Charfield
custom_variables = Dictionaryfield. (holds other data about what they have done or not)
I just realized that I may want the mission description to depend on membermisson variables (eg. perhaps we give more time or less time or vary the reward based on these variables).
So, in the template, rather than showing the field mission.description, I should show a function (get_description) that pulls the description and modifies it based on the membermission data.
My question is this, where would a Django pro put this function?
Should it be on the Membermission
Eg) membermission.get_description()
Or should it be on the Mission
Eg) misson.get_description(membermission)
Or should I have it as a seperate function in some toolbox file (and put it into a template tag)
Eg) toolbox.get_description(membermission)
Or should I just find a source for Adderall and get over all this?
Thank you so much everyone.
/r/django
https://redd.it/696rdp
reddit
Are there best practices for organizing methods between... • r/django
Hi everyone, I have been working with Django for a while and I really dig it. However I often feel I overcomplicate my code and get lost at...