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
Social Groups in Django

Let's say I have an 'articles' app. A user who belongs to 'Group A' publishes an article. This article can only be read by the members of 'Group A.' 'Group A' also has a superuser but his permissions are only valid for users in 'Group A.' How would I go about implementing this?

/r/django
https://redd.it/8o9ysg
Super Beginner Python question.

Hi all,

I am currently programming some descriptive analytics on a CSV file.

I have imported using Pandas as far as I know.

My general aim; Create a bar chart of Location occurrence within the CSV file

The image below is as far as I have got but this is not all of the variables.

I am wondering if there is a way of importing the 'many' different locations as separate variables as I need to add 1 to each variable when the regex is matched against the CSV.

The CSV column is called; \(Some are abbreviated for ease as variables\)

**Borough**

>COL = 0
>
>Barnet = 0
>
>Bexley = 0
>
>BAD = 0
>
>Brent = 0
>
>Bromley = 0
>
>Camden = 0
>
>Croydon = 0
>
>Ealing = 0
>
>Enfield = 0
>
>Greenwich = 0
>
>Hackney = 0
>
>HAF = 0
>
>Haringey = 0
>
>Harrow = 0
>
>Havering = 0
>
>Hillingdon = 0
>
>Hounslow = 0
>
>Islington = 0
>
>KAC = 0
>
>KUT = 0
>
>Lambeth = 0
>
>Lewisham = 0
>
>Merton = 0
>
>Newham = 0
>
>Redbridge = 0
>
>RUT = 0
>
>Southwark = 0
>
>Sutton = 0
>
>TowerHamlets = 0
>
>WalthamForest = 0
>
>Wandsworth = 0
>
>Westminster = 0
>
>OuterBorough = 0
>
>InnerBorough = 0

Here is my current code with the output of the image below:

#Start of Imports
import csv
import sys
import numpy as np
import pandas as pd
import re
import matplotlib.pyplot as plt
#End of Imports

#Start of Declarations
COL = 0
Barnet = 0
Bexley = 0
BAD = 0
Brent = 0
Bromley = 0
Camden = 0
Croydon = 0
Ealing = 0
#This is as far as I got when I thought something was wrong?
Enfield = 0
Greenwich = 0
Hackney = 0
HAF = 0
Haringey = 0
Harrow = 0
Havering = 0
Hillingdon = 0
Hounslow = 0
Islington = 0
KAC = 0
KUT = 0
Lambeth = 0
Lewisham = 0
Merton = 0
Newham = 0
Redbridge = 0
RUT = 0
Southwark = 0
Sutton = 0
TowerHamlets = 0
WalthamForest = 0
Wandsworth = 0
Westminster = 0
OuterBorough = 0
InnerBorough = 0
#End of Declarations

#Starts reading 'csv file'
csv = pd.read_csv ('land-area-population-density-london.csv') #Not sure what this does, index_col=3)

#Start of IF Statement
csva = np.array(csv)
for column in np.arange(0, csva.shape[0]):
if re.match(r"Barnet", str(csva[column][2])) is not None:
Barnet = Barnet + 1
elif re.match(r"Bexley", str(csva[column][2])) is not None:
Bexley = Bexley + 1
elif re.match(r"City of London", str(csva[column][2])) is not None:
COL = COL + 1
elif re.match(r"Barking and Dagenham", str(csva[column][2])) is not None:
BAD = BAD + 1
elif re.match(r"Brent", str(csva[column][2])) is not None:
Brent = Brent + 1
elif re.match(r"Bromley", str(csva[column][2])) is not None:
Bromley = Bromley + 1
elif re.match(r"Camden", str(csva[column][2])) is not None:
Camden = Camden + 1
elif re.match(r"Croydon", str(csva[column][2])) is not None:
Croydon = Croydon + 1
elif re.match(r"Ealing", str(csva[column][2])) is not None:
Ealing = Ealing + 1
#End of IF Statement

#Start of graph fields
#Below: Places is the labels for the placesvar
places = ('Barnet', 'Bexley', 'City of London', 'Barking and Dagenham', 'Brent', 'Bromley', 'Camden', 'Croydon', 'Ealing')
#Below: placesvar the actual 'places' pulled from CSV
placesvar = [Barnet, Bexley, COL, BAD, Brent, Bromley, Camden, Croydon, Ealing]
#Y Positioning numpy.arange (Again no idea what this does) length 'places pulled from csv'
y_pos = np.arange(len(placesvar))
#End of graph fields

#Start of Graph positions and Names
plt.bar(y_pos, placesvar, align='center')
plt.xticks(y_pos, places, rot
ation=60)
plt.ylabel('No. of occurance')
plt.xlabel('Locations')
plt.title('Occurance of Locations')
#plt.savefig('file.png')(Commented out for testing)
#End of Graph positions and Names
plt.show()



https://i.redd.it/n311chii2u111.png

/r/Python
https://redd.it/8oat6s
DRF+Django

Hi there,

So we're fairly new to Django and wish to make a backend using it for a RN app. The DB needs to be Postgres. Therefore my question was how does DRF/Django sit in this? Does Django get installed/used for the migrations as a prerequisite for DRF? As the client will then be querying the DB through DRF as the API.

/r/django
https://redd.it/8obdfb
Moving a locally hosted Flask App to another computer

I have a flask app that is saved on my computer and if I want to save it in a zip archive, then move it to another computer, using USB, can I still be able to run it standalone, or does the other PC need Python installed?

I'm using MySQL database and a virtual environment so I know I need some kind of a local server (like WAMP) to run it, but I'm not so sure about Python and it's dependencies. Are they standalone in the Virtual Environment or are they still dependend on the root Python files?

I'm asking this because I need to show the project in my school but don't want to host it on the web just yet.

/r/flask
https://redd.it/8obuj1
i regexed all the commands from the very book i'm learning, for using as a personal cheat sheet [i am learning please dont judge :) ]

/r/Python
https://redd.it/8obvye
Best (fastest) algorithm to do this task ?

I'm creating a spell checker \(not for English\). For that I need to generate permutation for each word.

Lets assume the word is **jumbo** . And I have a dictionary with permutations stored.

dict = {
'u' : [ 'e','o' ],
'm' : [ 'n' ],
'o' : ['u']
}

From this I need to create all instances of the word with replacing the letter which is the key of the dictionary with the words of the values of each key. As an example, for **jumbo** according to *dict* dictionary there can be permutations like **jembo, jombo, janbo, jambu, jenbo, jonbo, jembu, jombu, janbu, jenbu, jonbu** . So, how can I generate all these combinations and generate all these permutation words ? I'm pretty sure I can do this with some nested loops. But what is the most efficient way ?

/r/Python
https://redd.it/8od6yd
Django & JSONField & SqlLite - '

I have no idea where to ask this so I am starting here.

I am trying to write a django application \(my first\). In so doing, I am using a SQLite database. I have some data stored in JSON into a JSON Field:

`class Data(models.Model):`

`data = JSONField()`

the data stored in the data base in the data field is text like this:

`[`

`{`

`"datetime": "2018-05-31T00:00:00.000Z",`

`"value": 90`

`}`

`]`

in the HTML, I have at the end of the document:

`<script>`

`{% for data in datas %}`

`var x{{` [`data.id`](https://board.id) `}} = {{` [`data.data`](https://board.data) `}};`

`{% endfor %}`

`</script>`

but instead of creating var x1 with some json in it, I get:

var x1 = \[{AMPERSAND#39datetimeAMPERSAND#39: AMPERSAND#392018\-05\-31T00:00:00.000ZAMPERSAND#39, AMPERSAND#39valueAMPERSAND#39: 90}\]

Where you replace AMPERSAND with & because &# 39 doesn't show up right here.

All of the original double quotes in the database are replaced with &#39, which actually the ascii code for apostraphe. Do you guys have any tips for how I can have json in the database and get it out through django?

/r/django
https://redd.it/8oefeu
Concurrency issue? Standalone python script sharing settings.py and ORM with django server has unreliable view of DB objects?

I'm having a strange problem that is difficult to reproduce (everything worked 2 days ago but some time between then and now no longer does--with no changes in the interim!)

I have a django server program which we are running via gunicorn with multiple worker subprocesses and a separate small REST webservice which shares the settings.py of the server program and acts on the same DB objects. The code for this server program is roughly as follows:

# my app's models.py
class TestConfig(models.Model):
## various attributes
class Test(models.Model):
## some attributes
def startTest(self):
return TestExecution.objects.create(test=self)
class TestExecution(models.Model):
test = models.ForeignKey(
Test,
on_delete=models.CASCADE
)
config = models.ForeignKey(
TestConfig,
on_delete=models.CASCADE,
null=True
)

# excerpt from a post() method in my app's views.py
test = Test.objects.get(test_id)
if config_form.is_valid():
config = config_form.save()
config_id = config.id
test_exe = test.startTest()
test_exe.config = config
test_exe.save()

webservice_response = requests.get(
'http://{}:{}/rest/add_to_queue/{}'.format(
webservice_ip, webservice_port, test_exe.id))

The other program (small REST webservice) sharing the same settings.py as the django server program looks as follows:

os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings'
import django
django.setup()

# the REST endpoint referenced from the django server program
@app.route('/rest/add_to_queue/<test_exe_object_id>/')
@app.route('/rest/add_to_queue/<test_exe_object_id>')
def add_to_queue(test_exe_object_id):
from myapp.models import TestExecution
try:
exe_object = TestExecution.objects.get(pk=int(test_exe_object_id))

# for completeness the database section of my settings.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'test_db',
'USER': 'root',
'PASSWORD': 'root',
'HOST': 'localhost',
'PORT': '3306',
'OPTIONS': {
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
},
}
}

As I said, this was working fine a few days ago, then when I tried again today I was getting a DoesNotExist in the second program when trying to "get()" the TestExecution object using its 'id'.
Does anyone have experience with this or a similar issue?

/r/django
https://redd.it/8o9b8c
Question about AWS and hosting a subdomain running flask next to a wordpress site on EC2

Is it really just as easy as following \[this\]\([https://www.brianshim.com/webtricks/host\-multiple\-sites\-amazon\-ec2/](https://www.brianshim.com/webtricks/host-multiple-sites-amazon-ec2/)\) tutorial and then building the app in the documentRoot directory dictated in the httpd.conf?

Any insight would be apppriciated.

I just want to be able to put \(possibly a few\) flask apps next to my wordpress blog. For example wordpress blog would be at spacebucketfu.com and the flask app would be app.spacebucketfu.com

/r/flask
https://redd.it/8oebsp
How can I read a client's IP address in a Jupyter Notebook?

Hello,

Is it possible to read an IP address in a Notebook?

I have multiple people connecting to a Notebook and I need to store their IP addresses.

I can see them in the Jupyter log file, but is there anyway I can use Python code to get the IP address of whoever is running the Notebook?

Each client connection needs to have a folder created with a name based on his or her IP address to store Excel processing output.

/r/IPython
https://redd.it/8oeros
Dynaconf 1.0.x released - Layered configuration system for python with flask and django support
http://brunorocha.org/python/dynaconf-1-0-x-released-layered-configuration-system-for-python-with-flask-and-django-support.html

/r/flask
https://redd.it/8nkt33
Automating the Creation of the Demonstration GIF for README

So I was creating a GIF for the GitHub README of a terminal project I am working on and, since I didn't want to have to do the demo all over again if I wanted to make a small change, I wrote a little program that automates the demonstration. What it does basically is read the keys I want to type from a text file that also has certain "flags" embedded in it that trigger events like changing the typing delay speed, sleep for N seconds, send Enter/Tab/Escape/Ctrl+U to the terminal, etc. This way the whole transcript for the demo is stored in a text file. If I need to change something in the future, I can just edit the text file, rerun `autodemo`, and then sit back and wait. Here's a link to the script: https://github.com/bbugyi200/scripts/blob/master/bin/main/autodemo

As an example, take this transcript file: https://github.com/bbugyi200/localalias/blob/master/docs/img/demo.txt

I used that file (with `autodemo`) to produce the GIF that is in the README of this project: https://github.com/bbugyi200/localalias

Anyway, I wanted to know if anyone has heard of something like this that I should be using instead? Or if this little script actually has any value? I fully expect the former and would rather use a more mature solution if available. Thanks in advance!

/r/Python
https://redd.it/8oj2mw
How to manage shared Python packages in a microservice architecture?

I'm in the process of decoupling and splitting our monolith app into a few different services. There are a few modules we'd like to turn into python packages in order to reuse across the board in the new services and I'm not sure what's the “standard” method to distribute and control the dependencies. How is everyone managing many private Python packages in a microservice architecture?


Is a private Pypi server required or can we use github directly? What about pip on the services consuming those packages? how is version management done? \(specifically bumping versions up...\)


Would love any kind of input.
Thanks!


/r/Python
https://redd.it/8ol9jg
Beginner/I know the basics - Where to go next?

Hi, I took a python class this past semester and I have a decent handle on everything in Zelle's "Python Programming" (which goes through everything from functions to simulation/data collections/OOD) but so far I've just been solving random assigned problems, and I dont really know where to go next with Python. I've been doing a little bit with tkinter but I'm not sure how useful that even is. I feel like I learned a lot but I dont know where to go next, so if anyone has any advice I'd appreciate any help. My only idea so far is to look into using python with ArcGIS.

/r/Python
https://redd.it/8olzr7