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
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
A website to look for Django function/class names and import paths

I always forget certain function/class import paths and I thought a website could come in handy so I created one: http://dilu.karthus.net/ ^^^The ^^^source ^^^code ^^^is ^^^available ^^^here: ^^^https://github.com/kviktor/dilu

/r/django
https://redd.it/5lulzy
Can't seem to figure out why I keep ending up with an empty dictionary, care to check it out?

Here's some code from a prof who is teaching an online course (it's through a MOOC, so I can't really ask him directly).

import urllib
url = 'http://www.py4inf.com/code/romeo.txt'
fhand=urllib.urlopen(url)

counts = dict()
for line in fhand:
words = line.split()
for word in words:
counts[word] = counts.get(word, 0) + 1

print counts

I expected a dictionary containing something to the effect of 'some_word: # of occurrences of some_word' but I just get an empty dictionary. I'm running Python 2.7 inside a Jupyter notebook if that helps.

Edit: I think I fixed it. I forgot to use counts.iteritems() to print out the words and their counts. Though, I'm still wondering why I can't view the dictionary.

/r/Python
https://redd.it/5lwkzn
What's that Python script that you could use to generate text to speech from a bunch of sound files?

Is anyone aware of a python module that would use as many voice files one feeds it to generate a usable cache of files to use for text to speech conversion? I am fairly certain I came across it here.

/r/Python
https://redd.it/5lwit4
[AF]Flask routes not working

Hi guys, I'm trying to setup my own server for the first time and I'm running Ubuntu Server 15.04 with nginx and gunicorn.
I'm following that tutorial https://realpython.com/blog/python/kickstarting-flask-on-ubuntu-setup-and-deployment/, and everything is all right, but I can't make flask follow my routes. I can even set a different 404 error (that's how I figured flask was running). Can I get some help here?

from flask import Flask, jsonify, request

app = Flask(__name__)

@app.errorhandler(404)
def page_not_found(error):
return 'Rota com problema {}'.format(request.url), 404

@app.route("/")
@app.route("/index")
def index():
return 'Flask is running!'


@app.route('/data')
def names():
data = {"names": ["John", "Jacob", "Julie", "Jennifer"]}
return jsonify(data)


if __name__ == '__main__':
app.run()

There's my app.py.

I can provide other files and so related to the project.

Edit: Did some further testing and it works all right when I use "curl localhost:8000" or "curl localhost:8000/data". The issue is with my server and not flask???

Edit2: it was nginx and not my app, both nginx and flask are really bad at reporting errors and issues, geez. Nginx was redirecting to localhost:8000 and I was testing against localhost:8000/. Just added that extra slash after the host and everything is fine.

/r/flask
https://redd.it/5lsvss
[P] Pre-trained RNN chatbot

Here is a [pre-trained TensorFlow-powered chatbot](https://github.com/pender/chatbot-rnn) that was trained on many gigabytes of Reddit conversations for over 37 days with a Titan X GPU.

The underlying model is a character-based sequence predictor and it uses optional beam search and relevance masking/MMI to formulate its responses. It comes with a python script for interactive chatting.

A sample dialogue transcript (which was not cherry-picked) is included in the github readme.

Also included is a python script to assemble conversations from raw Reddit data, which I hope may be of interest for other similar projects.

/r/MachineLearning
https://redd.it/5lx7px
Help with a simple Python program / just learning

Hello,

I have been working through tutorials and such but am still a newbie at Python. I decided to try writing a simple program from scratch in order to further my learning.

The goal of the program is to take word (text string) as input, count the vowels (I didn't include Y in order to make it simple as why is not always a vowel) and output the number of vowels back to the user. Here is what I have so far:

# Written in Python 2.7
# Attempting to count the vowels within a string and
# output that count to the user.
vowelList = ["a", "e", "i", "o", "u"]
vowelCount = 0

print "Please type in a word."
print "This program will count the number of vowels in that word."
userWord = raw_input("What is your word? ")

wordLength = len(userWord)
print wordLength

for (vowelList) in (userWord):
vowelCount += 1
print vowelCount

Note: what this program actually does is

Return the total length of the word
count each element in the list and return those one by one.

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