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
Year of Programming Challenge!

Hello all, there was a post over at r/learnprogramming, it was a thread about people wanting to code everyday for this year. the community outgrew the groupme chat, and grew into a slack channel where we are sitting at 300+ members, and have 60 people forked the github repository. I thought it was a super cool idea and wanted to share it with people over here who wanted to sharpen their python programming skills!

A github organization was created where challenges can be posted and people can submit pull-requests and get their work merged with the organizations master repository. this is amazing as it will help keep our skills sharp, and start to build a github reputation thatll look good to recruiters.


heres the slack channel: https://yearofprogramming.slack.com/shared_invite/MTIyNDM3Mjc1OTI1LTE0ODMzMDQwMzAtOGNkNTA2NDY5Yg


and the github org repo: https://github.com/YearOfProgramming/2017Challenges

/r/Python
https://redd.it/5lnxtp
Trying to make my own version of django-admin startproject. Have I created a monster?

I'm currently learning Django, specifically how to create a new project. I was taught to use the command
django-admin startproject {project name}
in bash and then modify some of the files it created. I thought that modifying the same files in the same way every time I made a new Django project was inefficient, so I wrote a shell script that would create the files for me, already modified to how they needed to be.

It seemed like a good idea at the time, but now I'm getting a whole bunch of errors I don't understand. Have I created a monster I can no longer control? Any help is appreciated.

Here is my shell script:
new_django.sh

# Activate Django Virtual Envirnoment
source ~/Desktop/PYTHON/myEnvironments/djangoEnv/bin/activate

# Get names of project and app
echo "Enter project name:"
read project_name
echo "Enter application name:"
read app_name
echo "Copy the following string to be used as a secret key:"
python ~/Desktop/PYTHON/Django/secret_key.py
read secret_key

# Create Django Project
mkdir $project_name
cd $project_name

touch manage.py
echo "#!/usr/bin/env python\nimport os\nimport sys\n\nif __name__ == \"__main__\":\n\tos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"$project_name.settings\")\n\ttry:\n\t\tfrom django.core.management import execute_from_command_line\n\texcept ImportError:\n\t\t# The above import may fail for some other reason. Ensure that the\n\t\t# issue is really that Django is missing to avoid masking other\n\t\t# exceptions on Python 2.\n\t\ttry:\n\t\t\timport django\n\t\texcept ImportError:\n\t\t\traise ImportError(\n\t\t\t\t\"Couldn't import Django. Are you sure it's installed and \"\n\t\t\t\t\"available on your PYTHONPATH environment variable? Did you \"\n\t\t\t\t\"forget to activate a virtual environment?\"\n\t\t\t)\n\t\traise\n\texecute_from_command_line(sys.argv)\n" >> manage.py

touch db.sqlite3
echo -n -e "\x53\x51\x4c\x69\x74\x65\x20\x66\x6f\x72\x6d\x61\x74\x20\x33\x00\x10\x00\x01\x01\x00\x40\x20\x20\x00\x00\x00\x01\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00..." >> db.sqlite3

mkdir $project_name
cd $project_name

touch __init__.py

touch settings.py
echo "\"\"\"\nDjango settings for $project_name project.\n\nGenerated by 'new_django.sh' using Django 1.10.3.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.10/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.10/ref/settings/\n\"\"\"\n\nimport os\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = '$secret_key'\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\n\nALLOWED_HOSTS = []\n\n\n# Application definition\n\nINSTALLED_APPS = [\n\t'apps.$app_name',\n\t'django.contrib.admin',\n\t'django.contrib.auth',\n\t'django.contrib.contenttypes',\n\t'django.contrib.sessions',\n\t'django.contrib.messages',\n\t'django.contrib.staticfiles',\n]\n\nMIDDLEWARE = [\n\t'django.middleware.security.SecurityMiddleware',\n\t'django.contrib.sessions.middleware.SessionMiddleware',\n\t'django.middleware.common.CommonMiddleware',\n\t'django.middleware.csrf.CsrfViewMiddleware',\n\t'django.contrib.auth.middleware.AuthenticationMiddleware',\n\t'django.contrib.messages.middleware.MessageMiddleware',\n\t'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\nROOT_URLCONF = '$project_name.urls'\n\nTEMPLATES = [\n\t{\n\t\t'BACKEND': 'django.template.backends.django.Django
Templates',\n\t\t'DIRS': [],\n\t\t'APP_DIRS': True,\n\t\t'OPTIONS': {\n\t\t\t'context_processors': [\n\t\t\t\t'django.template.context_processors.debug',\n\t\t\t\t'django.template.context_processors.request',\n\t\t\t\t'django.contrib.auth.context_processors.auth',\n\t\t\t\t'django.contrib.messages.context_processors.messages',\n\t\t\t],\n\t\t},\n\t},\n]\n\nWSGI_APPLICATION = '$project_name.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/1.10/ref/settings/#databases\n\nDATABASES = {\n\t'default': {\n\t\t'ENGINE': 'django.db.backends.sqlite3',\n\t\t'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),\n\t}\n}\n\n\n# Password validation\n# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators\n\nAUTH_PASSWORD_VALIDATORS = [\n\t{\n\t\t'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n\t},\n\t{\n\t\t'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n\t},\n\t{\n\t\t'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n\t},\n\t{\n\t\t'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n\t},\n]\n\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.10/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.10/howto/static-files/\n\nSTATIC_URL = '/static/'\n\n" >> settings.py

touch urls.py
echo "\"\"\"$project_name URL Configuration\n\nThe \`urlpatterns\` list routes URLs to views. For more information please see:\n\thttps://docs.djangoproject.com/en/1.10/topics/http/urls/\nExamples:\nFunction views\n\t1. Add an import: from my_app import views\n\t2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n\t1. Add an import: from other_app.views import Home\n\t2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n\t1. Import the include() function: from django.conf.urls import url, include\n\t2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url, include\n# from django.contrib import admin\n\nurlpatterns = [\n\turl(r'^', include('apps.$app_name.urls')),\n]" >> urls.py

touch wsgi.py
echo "\"\"\"\nWSGI config for $project_name project.\n\nIt exposes the WSGI callable as a module-level variable named \`\`application\`\`.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/\n\"\"\"\n\nimport os\n\nfrom django.core.wsgi import get_wsgi_application\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"$project_name.settings\")\n\napplication = get_wsgi_application()\n" >> wsgi.py

cd ..

mkdir apps
cd apps

touch __init__.py

mkdir $app_name
cd $app_name

touch __init__.py

touch admin.py
echo "from django.contrib import admin\n\n# Register your models here.\n" >> admin.py

touch apps.py
echo "from __future__ import unicode_literals\n\nfrom django.apps import AppConfig\n\n\nclass AppNameConfig(AppConfig):\n\tname = '$app_name'\n\n" >> apps.py

mkdir migrations
cd migrations

touch __init__.py

cd ..

touch models.py
echo "from __future__ import unicode_literals\n\nfrom django.db import models\n\n# Create your models here.\n" >> models.py

mkdir templates
cd templates

mkdir $app_name
cd $app_name

touch index.html
echo "<!DOCTYPE html>\n<html>\n\t<head>\n\t\t<title>$project_name</title>\n\t</head>\n\t<body>\n\t\t<h1>$app_name</h1>\n\t</body>\n</html>\n" >> index.html

cd ..

cd ..
touch tests.py
echo "from django.test import TestCase\n\n# Create your tests here.\n" >> tests.py

touch urls.py
echo "from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n\turl(r'^.*$', views.index),\n]\n" >> urls.py

touch views.py
echo "from django.shortcuts import render\n\n# Create your views here.\n\ndef index(request):\n\treturn render(request,\"$app_name/index.html\")\n" >> views.py

cd ..

cd ..

# python manage.py migrate

# echo "Application $app_name created in $project_name"

And here are the errors I'm getting:

Enter project name:
lemon
Enter application name:
tiger
Copy the following string to be used as a secret key:
052cif$=_$043%ffntthkm@-n*evj6wtre64xk@_sgv1fjirr@
052cif$=_$043%ffntthkm@-n*evj6wtre64xk@_sgv1fjirr@
(djangoEnv) JesusIsMyZolofts-MacBook-Pro:test JesusIsMyZoloft$ cd lemon
(djangoEnv) JesusIsMyZolofts-MacBook-Pro:lemon JesusIsMyZoloft$ python manage.py migrate
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/Users/JesusIsMyZoloft/Desktop/PYTHON/myEnvironments/djangoEnv/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
utility.execute()
File "/Users/JesusIsMyZoloft/Desktop/PYTHON/myEnvironments/djangoEnv/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/JesusIsMyZoloft/Desktop/PYTHON/myEnvironments/djangoEnv/lib/python2.7/site-packages/django/core/management/base.py", line 294, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/JesusIsMyZoloft/Desktop/PYTHON/myEnvironments/djangoEnv/lib/python2.7/site-packages/django/core/management/base.py", line 345, in execute
output = self.handle(*args, **options)
File "/Users/JesusIsMyZoloft/Desktop/PYTHON/myEnvironments/djangoEnv/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 83, in handle
executor = MigrationExecutor(connection, self.migration_progress_callback)
File "/Users/JesusIsMyZoloft/Desktop/PYTHON/myEnvironments/djangoEnv/lib/python2.7/site-packages/django/db/migrations/executor.py", line 20, in __init__
self.loader = MigrationLoader(self.connection)
File "/Users/JesusIsMyZoloft/Desktop/PYTHON/myEnvironments/djangoEnv/lib/python2.7/site-packages/django/db/migrations/loader.py", line 52, in __init__
self.build_graph()
File "/Users/JesusIsMyZoloft/Desktop/PYTHON/myEnvironments/djangoEnv/lib/python2.7/site-packages/django/db/migrations/loader.py", line 203, in build_graph
self.applied_migrations = recorder.applied_migrations()
File "/Users/JesusIsMyZoloft/Desktop/PYTHON/myEnvironments/djangoEnv/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations
self.ensure_schema()
File "/Users/JesusIsMyZoloft/Desktop/PYTHON/myEnvironments/djangoEnv/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 52, in ensure_schema
if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()):
File "/Users/JesusIsMyZoloft/Desktop/PYTHON/myEnvironments/djangoEnv/lib/python2.7/site-packages/django/db/backends/base/introspection.py", line 57, in table_names
return get_names(cursor)
File "/Users/JesusIsMyZoloft/Desktop/PYTHON/myEnvironments/djangoEnv/lib/python2.7/site-packages/django/db/backends/base/introspection.py", line 52, in get_names
return sorted(ti.name for ti in self.get_table_list(cursor)
File "/Users/JesusIsMyZoloft/Desktop/PYTHON/myEnvironments/djangoEnv/lib/python2.7/site-packages/django/db/backends/sqlite3/introspection.py", line 68, in get_table_list
ORDER BY name""")
File "/Users/JesusIsMyZoloft/Desktop/PYTHON/m
yEnvironments/djangoEnv/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/Users/JesusIsMyZoloft/Desktop/PYTHON/myEnvironments/djangoEnv/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/Users/JesusIsMyZoloft/Desktop/PYTHON/myEnvironments/djangoEnv/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/Users/JesusIsMyZoloft/Desktop/PYTHON/myEnvironments/djangoEnv/lib/python2.7/site-packages/django/db/backends/utils.py", line 62, in execute
return self.cursor.execute(sql)
File "/Users/JesusIsMyZoloft/Desktop/PYTHON/myEnvironments/djangoEnv/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 335, in execute
return Database.Cursor.execute(self, query)
django.db.utils.DatabaseError: file is encrypted or is not a database

/r/django
https://redd.it/5lmfz1
Major issue with templates, not updating

I have no idea how this happened, but whenever I update my templates/views/etc it updates as expected. However if you keep refreshing any page on the site it shows an old template randomly. Say if you refresh the site 6 times half the times it will show an old template. If you go to a new page and keep refreshing it, it will 404 as if it doesn't exist.

It's almost like there are two instances going on - if you keep refreshing it goes back and forth.

I've tried clearing my cache and restarting the server. VERY confusing

/r/django
https://redd.it/5llt8h
[AF] Storing class object across requests?

Hi all, I'm learning Flask by attempting to build a Blackjack game.

Currently, I have a few views defined as well some of the game logic in a file/module called `game.py`.

What I'm currently doing:
The user visits the `trygame.html` page where the game can be played without the user having to register/sign in. For the future, I intend to create a full fledged game that includes leaderboards and game setting options.

What I am having issues with:
Right now, I am simply attempting to deal a new card from a `Shoe` (representing a dealer's shoe) object. This works. HOWEVER: Everytime I hit "Deal card" the object appears to reinitialize itself. Obviously, I want to avoid this until the `Shoe` is empty.

An excerpt of my `game.py` file:


class Blackjack(object):
def __init__(self):
pass

NO_OF_DECKS = 1

SUITS = ['clubs', 'spades', 'diamonds', 'hearts']

RANKS = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']

VALUES = {'A': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8,
'9': 9, '10': 10, 'J': 10, 'Q': 10, 'K': 10}


class Shoe(Blackjack):
""" Creates a new shoe object from which cards are dealt
to the player and the dealer.

Input arguments:
decks :: the number of decks the player wishes to play with.
"""
def __init__(self, decks=1):
self.cards_in_shoe = {}
self.total_cards = decks * 52
for i in Blackjack.SUITS:
self.cards_in_shoe[i] = Blackjack.RANKS * decks

def get_random_card(self):

random_suit = random.choice(self.cards_in_shoe.keys())
cards_in_suit = self.cards_in_shoe[random_suit]
random_card = random.choice(cards_in_suit)

cards_in_suit.remove(random_card)

# deleting suit if cards exhausted.
if len(self.cards_in_shoe[random_suit]) == 0:
del self.cards_in_shoe[random_suit]

return (random_suit, random_card)

def remaining_cards_in_shoe(self):
""" Returns the total number of cards remaining to be
drawn for both player and dealer.
"""
return sum(len(v) for v in self.cards_in_shoe.itervalues())

Using the terminal/command line, everything works.

Here is my current `trygame` view: (not working)

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

shoe = game.Shoe()
card = shoe.get_random_card()
remaining_cards = shoe.remaining_cards_in_shoe()

return render_template('trygame.html',
card=card,
remaining_cards=remaining_cards)

Now, I understand that every time we render the page, we initialize a new `Shoe` object, which is obviously incorrect.

So now I'm thinking what is the proper way of dealing with this. Is it current_app? Is it session? Is it something else?

I'm strongly tending towards session, so I'm thinking something like this:

@app.route('/trygame', methods=['GET', 'POST'])
def trygame():
# I believe this is the way to go, but it won't work
print session

if request.method == 'POST':
card = session['shoe'].get_random_card()
remaining_cards= session['shoe'].remaining_cards_in_shoe()
return render_template('trygame.html',
card=card,
remaining_cards=remaining_cards)

session['shoe'] = game.Shoe()
card = session['shoe'].get_random_card()
remaining_cards = session['shoe'].remaining_cards_in_shoe()

return render_template('trygame.html',
card=card,
remaining_cards=remaining_cards)

Unfortunately however, I am unable to store the object in the session variable, as it's not JSON encodable. And if I
force it to JSON, then I obviously cannot call methods on it, as they don't exist.

Long story short, how do I get this to work correctly? Also, if session is the way to go here, how do I keep the user from seeing the content of available cards in shoe, as well as the dealers hand value (something I will have to deal with in the future..)

Thank you so much in advance.
The GitHub link: https://github.com/mmenschig/flaskJack

/r/flask
https://redd.it/5lqmkj
[AF] Is it possible to display data from a list and provide a download link?

I have created a Flask app that creates a list and returns the list to an HTML page. I would also like to make the list downloadable as a CSV file.

So far I understand how to do these tasks as separate functions.

Is there a way to combine these functions into one so that a list is created only once, displaying the data on an HTML template, and also providing a download link?

Please view the basic examples below:

[Flask code](http://pastebin.com/yxd41Ste)


[Template](http://pastebin.com/TNBQUy6R)

/r/flask
https://redd.it/5lrnmt
Django app store/repository (django newbie)

I did a `pip search django` which returned >4000 modules, which is kinda useless for me. As a newbie I'm stuck with 2 issues:

* Browsing for applications -> Does Django have something akin to Docker's http://store.docker.com? A related question: Which 3rd party Django apps should an aspiring developer be aware of?

* Integration -> Any supporting tooling for this? Or is it "just" a matter of `git clone AppX` and manually editing config files?



/r/django
https://redd.it/5lr98i
Django+React

I'm a beginner-intermediate web developer.
As a personal project, I want to create a todo app for an imaginary company with the following features:
1. user can create, edit or delete a task (similar to the one shown in https://www.youtube.com/watch?v=IR6smI_YJDE&t=1791s)
2. each task can be marked "unstarted", "in progress" or "completed"
3. tasks can be sorted/filtered chronologically or in terms of their progress
4. users have to login to the system. There are 2 access levels: the employers can only view the tasks, whereas the boss can view and edit the tasks

I figured the frontend of 1-2 can be done with React, whereas the backend of 1-2, as well as 4 can be done with Django. (3 can be done with only JavaScript I guess) I have been learning bits and pieces of web development on my own, and I have no idea if this is the best practice? Is there another way to implement the features? Is it worth the effort integrating Django with React?

/r/django
https://redd.it/5lpu0q
What's everyone working on this week?

Tell /r/python what you're working on this week! You can be bragging, grousing, sharing your passion, or explaining your pain. Talk about your current project or your pet project; whatever you want to share.


/r/Python
https://redd.it/5ls2vr
Using Python to automatically create square-mile figure-ground diagrams of cities' street networks, to compare urban form anywhere in the world
http://geoffboeing.com/2017/01/square-mile-street-network-visualization/

/r/Python
https://redd.it/5lsuef
Can someone help? AttributeError: 'module' object has no attribute 'draw_all'

I need to plot live data from usb port and I'm using the lib "drawnow". However, when I try to run the code and it says the following: 'AttributeError: 'module' object has no attribute 'draw_all''. I've tried to update matplotlib but had an error because of permission denied. Can someone help me figure what I have to do? Or give any other solution to the problem?

CODE:

import serial

import matplotlib.pyplot as plt
from drawnow import *
import numpy
plt.ion()

serialAtmega = serial.Serial('COM6', baudrate=9600, stopbits=serial.STOPBITS_ONE)
ADC0array=[]
ADC1array=[]

def graphs ():
plt.plot(ADC0)

while True:

valueRead = str(serialAtmega.readline())

values = valueRead.split(',')
ADC0 = values[0].replace("b'","")
ADC1 = values[1].replace("\\r\\n'","")
ADC0array.append(ADC0)
ADC1array.append(ADC1)
drawnow(graphs)
plt.pause(0.00001)

/r/Python
https://redd.it/5ltuel