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
My first Python program :) (I'm hooked)

So, Python was on my list of things to teach myself after I took a C++ course this spring (I regret that, should have taken Python or Java).

So, I am proud of this stupid little dice roller because I evolved it from a basic "This rolls two dice" to "How many do you want to roll?" with input validation. Yay me.

#my first Python program.
#I chose this one to compare to a similar program made
in C++

import random
import time

roll = "yes"
numDice = 0


print("This program will roll as many dice as you need.")
time.sleep(1) #this makes the program pause a bit

print("\nWould you like to roll?")
roll = input()

#input validation to make sure they type yes (y) or no
(no)
while roll != "yes" and roll != "y" and roll != "no" and roll
!= "n":
print("\nType yes (or 'y') or no (or 'n') to roll.")
roll = input()

while roll == "yes" or roll == "y":
print("\nHow many dice do you want to roll?")
numDice = int(input())

print("\nRolling...")
time.sleep(2) #again, a pause

print("\nYou got: ")

for i in range(0, numDice): #this iterates as many times
as the user wants
print(random.randint(1,6)) #generates the random
numbers between 1-6

print("\nRoll again?")
roll = input()

#input validation again
while roll != "yes" and roll != "y" and roll != "no" and
roll != "n":
print("\nType yes or no.")
roll = input()


print("\nThanks for using my program!")

input()


/r/Python
https://redd.it/6hmq58
Quick reddit account migration script

Hey everyone, I haven't touched python in a while so I wanted to program a little script to migrate to a new account and wipe the old one (I'm a little paranoid about anonymity). Figured I would post it in hopes of some tips or critique, and maybe someone will find it useful. I also apologize if this isn't the right sub for this, didn't know where to post

import praw
#Account Migration Script
#By:/u/letmelive123
#Date:6/24/2017

#Warning! Using this script will entirely wipe the parent Account.
#To use input accounts and body to replace comments with
#parentAcc is the account being wiped
#secAcc is the account you are moving to
#body is the text that will replace all comments on parentAcc


#This function will transfer new multireddits to the target account.
#Note:We convert 'multi' to str and partition it to extract the multireddit name
#This is because parentAcc.user.multireddits() returns a list of paths to multireddits
def transferMultis():
for multi in parentAcc.user.multireddits():
s = str(multi)
parentAcc.multireddit(name=s.partition("/m/")[2], redditor=parentAcc.user.me()).update(visibility='public')
secAcc.multireddit(name=s.partition("/m/")[2], redditor=parentAcc.user.me()).copy(display_name=None)
parentAcc.multireddit(name=s.partition("/m/")[2],redditor=parentAcc.user.me()).delete()


#This function will transfer new multireddits to the target account.
def transferSubs():
for sub in parentAcc.user.subreddits():
s = str(sub)
secAcc.subreddit(s).subscribe()
parentAcc.subreddit(s).unsubscribe()

#This function will clean the comments of parentAcc.
def wipeComments(body):
for comment in parentAcc.redditor(name=str(parentAcc.user.me())).comments.top(time_filter='all'):
comment.edit(body)


###WARNING###
#This Account will be wiped
###WARNING###
#Parent Account
parentAcc = praw.Reddit(client_id='',
client_secret='',
password='k',
user_agent='AccMigrate by /u/letmelive123',
username='')

#Secondary Account
secAcc = praw.Reddit(client_id='',
client_secret='',
password='',
user_agent='AccMigrate by /u/letmelive123',
username='')

#Body for replacing comments
body="Test"

print("Hello welcome to AccMigrate.")
print("Please note wiping comments does take some time.")

transferMultis()
transferSubs()
wipeComments(body) print("done")


/r/Python
https://redd.it/6j6rpp
URL Confusion

I am following the django tutorial of thenewboston on Youtube. In tutorial number 12 he goes into creating a URL. I understand what the outcome is I just don't understand how it works or how I would write it myself. Here are the URL patterns.

urlpatterns = [
#/music/
url(r'^$', views.index, name='index'),

#/music/2
#This just blew my freaking mind
url(r'^(?P<album_id>[0-9]+)/$', views.detail, name="detail"),
]
If someone could help explain to me how the second URL works or point me towards an article that would explain it I would be very appreciative.

/r/djangolearning
https://redd.it/6zk5tn
Serializing a dictionary that is not a model in Django restframework

I have read a few answers and posts about serializing an dictionary . But I still can't get it to work. Here is the problem. I do some data processing in django app , and it returns this dictionary (It has information about a quiz):

{101: {'subject': 'General-Intelligence', 'topics': ['Coding Decoding', 'Dice & Boxes', 'Statement & Conclusion', 'Venn Diagram', 'Mirror and Water Image', 'Paper Cutting and Folding', 'Clock/Time', 'Matrix', 'Direction', 'Blood Relation', 'Series Test', 'Ranking', 'Mathematical Operations', 'Alphabet Test', 'Odd one out', 'Analogy'], 'num_questions': 25, 'creator': 'Rajesh K Swami'}}

I want to serialize this dictionary. So what I have done is created a class for this dictionary. ie.

class PsudoTests:

def __init__(self,body):
self.body = body

Also a serializer:

class PsudoTestSerializer(serializers.Serializer):
body = serializers.DictField()

Now in api view :

class TestListView(generics.ListAPIView):
def get_serializer_class(self):
serializer = PsudoTestSerializer
def get_queryset(self):
me = Studs(self.request.user)
tests = me.toTake_Tests(1) # this method brings in the above dictionary that i want to serialize
p_test = PsudoTests(tests) #this creates an instance of class created above

return p_test

Now when i go to the url there is a key error:

"Got KeyError when attempting to get a value for field body on serializer PsudoTestSerializer.\nThe serializer field might be named incorrectly and not match any attribute or key on the dict instance.\nOriginal exception text was: 'body'."


/r/django
https://redd.it/8apaxg
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
Flask-Admin SelectField Choices, not a valid option.

Hey, I got dynamic choices (selectfield choices depending on previous selectfield's data) working visually, but the problem seems to be, that the choices do not get updated in back end, and so it throws a validation error if I do not select from the original, hard coded selection.

Here is the ModelView example:

def scaffold_form(self):
form_class = super(TeacherTaskView, self).scaffold_form()

sport_choices = Sport.query.filter_by(type='')

form_class.sport2 = SelectField('Sport', choices=[(sport.id, sport.sport) for sport in sport_choices.all()], coerce=int)
#This is the hard coded first example choices
form_class.type = SelectField('Type', choices=[(int(type.id), type.type) for type in Sport.query.filter_by(sport='Kergejõustik').all()], coerce=int)

return form_class


def on_model_change(self, form, model, is_created):


/r/flask
https://redd.it/akfx0j
Access the text added using javascript to html file using flask.

I am trying to create a todo list using html, javascript and flask. In my todo list, I add my lists of tasks using javascript.

How can I print out my added list using python?

&#x200B;

`<!DOCTYPE html>`

`<html>`

`<head>`

`<title>Daily Goals</title>`

`<link rel="stylesheet" href="{url_for('static',filename='stylesheet/daily.css')}">`

`</head>`

`<body>`

`<script type="text/javascript" src="{url_for('static',filename='stylesheet/daily.js')}"></script>`

`<div class="addItem">`

`<input type="text" id="myInput" placeholder="text...">`

`<span onclick="newDiv()" class="addList">Add</span>`

`</div>`

`<form method='POST' action='/paras'>`

`<div class="covered" id="fullOn">`

`<h2 id="para">Add your daily todo lists</h2>`

`</div>`

`<div class="item"> #This is where my javascript will add my list.`

`<p>{itemName}</p>`

`</div>`

`<p><input value = "Do it" type='SUBMIT'></p>`

`</form>`

`</body>`

`</html>`

/r/flask
https://redd.it/c18sik
I just made the most 50/50 script ever: it selects and opens random image URLs from 4chan (returns NSFW results like half of the time)

It's fun to run! Cause you *really* never know what's going to pop up. Run at your own risk though, cause it can return anything from cute kitten pictures, to not-unseeable NSFL pictures

#!/usr/bin/python3
#*************************************************************************************************************************
#IMPORTANT
#Don't remove the time.sleeps; which are in place to comply with 4chan's API rule of 'no more than 1 request per second'
#https://github.com/4chan/4chan-API
#
#This script selects a random images from 4chan, and opens them in web browser
#Requires the 'requests' module
#*************************************************************************************************************************

import requests,random,json,time,webbrowser

#Returns [ random image URL, random image's thread URL ]
def r4chan():
#List of 4chan boards
boards = ['a','c','w','m','cgl','cm','n','jp','vp','v','vg','vr','co','g','tv','k','o','an','tg','sp','asp','sci','int','out','toy','biz','i','po','p','ck','ic','wg','mu','fa','3','gd','diy','wsg','s','hc','hm','h','e','u','d','y','t','hr','gif','trv','fit','x','lit','adv','lgbt','mlp','b','r','r9k','pol','soc','s4s']

#Select a board
board = random.choice(boards)

#Request board catalog, and get get a list of threads on the board; then sleeping for 1.5 seconds
threadnums = list()


/r/Python
https://redd.it/ccrh6o
My first useful script. Clear windows print server queue.

Greetings all!,

&#x200B;

This is my first useful python script, albeit a really simple one. It's purpose: At my place of work we have tons of clients that often try to print some weird ass files on the windows print server, only to lock it up.

It's not that hard to remote in to the server, stop the print service, clear the print queue, and restart the service. However, it is indeed tedious, and happens all too often affecting departments at a time. Therefore, I went ahead and made this script. It handles all those tasks for you. It needs to be ran as admin to work, and has an admin privilege checker in there. Not from scratch, I'm still new, I have taken a intro college course, but had to research some of these functions. It was not only copy and paste though, this was a learning experience for me as well.

Very useful for managed service providers, or the lazy sysadmin.

I call it: The spooler nuke.

#The purpose of this program is to kill the print service, delete print queue, restart print service.
#This script can be useful for clients who rely on the

/r/Python
https://redd.it/ef7324
Can I run AWS functions in Flask?

Hey all, I am looking to create a flask site that I can use my push buttons to run aws commands against my aws account, mainly to just run lambda functions I created. Was wondering if that was even possible? I have tried many things but still a no go. I posted below snippets of the code and wanted to see if I am on the right track if it is at all possible. flask site runs fine, just when I hit the push button it fails since im not sure if my code route is even functioned properly, I have also tried with just the def, also will be posted below

Thanks so much!

&#x200B;

from botofunctions import * #this is the file that holds functions

EXAMPLE1:
@app.route('/do_something', methods=['POST'])
def do_something():
msg = getcaller() # this function is just running aws sts g-c-i
return msg

EXAMPLE2:
@app.route('/do_something', methods=['POST'])
def do_something():


/r/flask
https://redd.it/gkhliq
How to get objects with certain foreignkey relationships in ORM?

Assume we have a product model:

`class Product(models.Model):`

`name = models.Charfield()`And a property model where possible properties are defined (like "price", "color", "weight"...):

`class Property(models.Model):`

`name = models.CharField()`

And we keep product properties in a separate model:

`class ProductProperty(models.Model):`

`propery = models.ForeignKey(Property)`

`product = models.ForeignKey(Product)`

`value = models.Charfield()`

I want to get product objects which have certain properties. For instance, **I want to get objects only if "price" and "color" is defined for them in ProductPropery table.**

I obtain the required properties as objects, but I could not solve how can I get products that have all of the given properties.

To rephrase, I'm looking for something like this:

`properties = Property.objects.filter(Q(name__contains="Price") | Q(name__contains="Color")) #this could return one or multiple property objects`

&#x200B;

`products = properties.productproperty_set.product_set # imaginary line I made up to show what I want to get`

I could only think of: looping through properties and sub-loop for related ProductProperties to get their products and create multiple lists, and then create a list that's made of common elements (products that are included in each list)

It would be great if you could help,

Best wishes

/r/django
https://redd.it/ihhszo
How to get objects with certain foreignkey relationships in ORM?

Assume we have a product model:

`class Product(models.Model):`

`name = models.Charfield()`

And a property model where possible properties are defined (like "price", "color", "weight"...):

`class Property(models.Model):`

`name = models.CharField()`

And we keep product properties in a separate model:

`class ProductProperty(models.Model):`

`propery = models.ForeignKey(Property)`

`product = models.ForeignKey(Product)`

`value = models.Charfield()`

I want to get product objects which have certain properties. For instance, **I want to get objects only if "price" and "color" is defined for them in ProductPropery table.**

I obtain the required properties as objects, but I could not solve how can I get products that have all of the given properties.

To rephrase, I'm looking for something like this:

`properties = Property.objects.filter(Q(name__contains="Price") | Q(name__contains="Color")) #this could return one or multiple property objects`

&#x200B;

`products = properties.productproperty_set.product_set # imaginary line I made up to show what I want to get`

I could only think of: looping through properties and sub-loop for related ProductProperties to get their products and create multiple lists, and then create a list that's made of common elements (products that are included in each list)

It would be great if you could help,

Best wishes

/r/django
https://redd.it/ihisa1
Way to loop np.save or np.savetxt?

I have very large data sets and so need to save by appending parts. The simplified version is below and I’m not sure why it doesn't work:

number = 10 #the number of iterations
thing = np.array(1,2,3)

f = open('a.npy', 'ab') #open a file for appending
for i in range(number):
np.save(f, thing) #save the thing to a file

with open('a.npy', 'rb') as f: #open a file for reading
a = np.load(f)
print(a) #this just returns 1,2,3 (not this ten times which is what I want).


I.e. I want to return [1,2,3,1,2,3,1,2,3,...,1,2,3]

/r/Python
https://redd.it/mpxahi