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
Question about Session from a Newbie

I have a email sign up page that takes in ?ref= referral codes and I've noticed something weird after I have entered one ?ref= , any further sign ups without a ?ref= will still use the referral code. I assume the ref data is stored for some time and is being used untill it is cleared or new data is entered.

Is this only an issue because I'm creating accounts from the same pc or would someone signing up from another location still have the ref stored in session?


Middleware


from joins.models import Join


class ReferMiddleware():
def process_request(self, request):
ref_id = request.GET.get("ref")
try:
obj = Join.objects.get(ref_id = ref_id)
except:
obj = None
if obj:
request.session['join_id_ref'] = obj.id


View


def home(request):
try:
join_id = request.session['join_id_ref']
obj = Join.objects.get(id=join_id)
except:
obj = None

form = JoinForm(request.POST or None)
if form.is_valid():
new_join = form.save(commit=False)
email = form.cleaned_data['email']
new_join_old, created = Join.objects.get_or_create(email=email)
if created:
new_join_old.ref_id = get_ref_id()
# add our friend who referred us to our join model or a related
if not obj == None:
new_join_old.friend = obj
new_join_old.ip_address = get_ip(request)
new_join_old.save()

#print all "friends" that joined as a result of main sharer email
#print Join.objects.filter(friend=obj).count()
#print obj.referral.all().count()

#redirect here
return HttpResponseRedirect("/%s" %(new_join_old.ref_id))

context = {"form": form}
template = "home.html"
return render(request, template, context)





/r/django
https://redd.it/5q4wnt
My code for Tic-Tac-Toe (beginner), compared to my mate that works at google's code.

Thought it would be interesting seeing someone beginner code, vs someone's professional code on the same project. After I sent him my code he replied with how he would have done it, as a comparison.

**My code:**

import random

def plyr1wintest(): #checks if player has 3 in a row
global winner
if (1 in plyr1list) and (2 in plyr1list) and (3 in plyr1list) or \
(4 in plyr1list) and (5 in plyr1list) and (6 in plyr1list) or \
(7 in plyr1list) and (8 in plyr1list) and (9 in plyr1list) or \
(1 in plyr1list) and (4 in plyr1list) and (7 in plyr1list) or \
(2 in plyr1list) and (5 in plyr1list) and (8 in plyr1list) or \
(3 in plyr1list) and (6 in plyr1list) and (9 in plyr1list) or \
(1 in plyr1list) and (5 in plyr1list) and (9 in plyr1list) or \
(3 in plyr1list) and (5 in plyr1list) and (7 in plyr1list):
print ((name1) + ' wins as X')
winner = True

def plyr2wintest(): #checks if player has three in a row
global winner
if (1 in plyr2list) and (2 in plyr2list) and (3 in plyr2list) or \
(4 in plyr2list) and (5 in plyr2list) and (6 in plyr2list) or \
(7 in plyr2list) and (8 in plyr2list) and (9 in plyr2list) or \
(1 in plyr2list) and (4 in plyr2list) and (7 in plyr2list) or \
(2 in plyr2list) and (5 in plyr2list) and (8 in plyr2list) or \
(3 in plyr2list) and (6 in plyr2list) and (9 in plyr2list) or \
(1 in plyr2list) and (5 in plyr2list) and (9 in plyr2list) or \
(3 in plyr2list) and (5 in plyr2list) and (7 in plyr2list):
print ((name2) + ' wins as O')
winner = True

def printboard(): #print board
print(' ')
print(' '+ position[0] +' | '+ position[1] +' | '+ position[2] + ' ' + ' '+ '1' +' | '+ '2' +' | '+ '3')
print('-----------' + ' ' + '-----------')
print(' '+ position[3] +' | '+ position[4] +' | '+ position[5] + ' ' + ' '+ '4' +' | '+ '5' +' | '+ '6')
print('-----------' + ' ' + '-----------')
print(' '+ position[6] +' | '+ position[7] +' | '+ position[8] + ' ' + ' '+ '7' +' | '+ '8' +' | '+ '9')
print(' ')

winner = False #win checker
movecount = 0 #counts amount of turns
playgame = True

print ('welcome to Noughts & Crosses') #title

while playgame == True:
position = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '] #sets the board spaces blank
plyr1list = []
plyr2list = []
gamelist = []

winner = False
movecount = 0

print (' ')
#Name input
print ('What is player 1s name?')
name1 = input()
print ('thanks '+ (name1) +', Whats player 2s name?')
name2 = input()
print ('so '+ (name1) +' is X and '+ (name2) + ' is O')
input("Press Enter to continue...")

printboard()

while (movecount < 9) and (winner == False):

if (movecount % 2 == 0): #player 1 turn

print ((name1) + 's ( X ) turn, please choose placement (1-9)')
move = input()
if move in ('1', '2', '3', '4', '5', '6', '7', '8', '9') and (int(move) not in (gamelist)):
plyr1list.append(int(move))
gamelist.append(int(move))
print (gamelist) #debug
position[int(move)-1] = ('X')
printboard()
movecount = movecount + 1
plyr1wintest()
elif move not in ('1', '2', '3', '4', '5', '6', '7', '8', '9'):
print ('That is not a valid move! Try again')
else: print ('That move is taken!, Try again')

else: #player 2 turn

print ((name2) + 's ( O ) turn, please choose placement (1-9)')
Flask program giving module not found

Im building a python web application with flask and uWSGI following this lovely guide https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-uwsgi-and-nginx-on-centos-7 and it worked marvels, the basic hello does indeed appear in the website hen loaded. I have installed every single module and dependency in the project file. Im trying now to build on the working script and I now my init.py file looks like this:


from flask import Flask
import pylab as pl
import numpy as np
import pandas as pd

from sklearn import svm
from sklearn import tree
import matplotlib.pyplot as plt
from sklearn import linear_model
from sklearn.pipeline import Pipeline
from sklearn.metrics import confusion_matrix
from sklearn.naive_bayes import MultinomialNB
from sklearn.linear_model import SGDClassifier
from mlxtend.plotting import plot_decision_regions
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer

app = Flask(__name__)

@app.route("/")


def hello():
data = pd.read_csv('test1.csv', error_bad_lines=False, delimiter=',')
numpy_array = data.as_matrix()
#print numpy_array

#text in column 1, classifier in column 2.
X = numpy_array[:,0]
Y = numpy_array[:,1]
Y=Y.astype(np.str)

#divide the test set and set the variable to their correct label/text
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.4, random_state=42)

#MultinomialNB
text_clf = Pipeline([('vect', CountVectorizer(stop_words='english')), ('tfidf', TfidfTransformer()),('clf', MultinomialNB()),])

text_clf = text_clf.fit(X_train.astype('U'),Y_train.astype('U'))
predicted = text_clf.predict(X_test)
# print the actual accuracy
print "MNB accuracy: ", np.mean(predicted == Y_test)

#make the confusion matrix
y_actu = pd.Series(Y_test, name='Actual')
y_pred = pd.Series(predicted, name='Predicted')
df_confusion = pd.crosstab(y_actu, y_pred)
print df_confusion

print"-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------$

#SVM
vect = CountVectorizer(min_df=0., max_df=1.0)
X = vect.fit_transform(X_train.astype('U'))
min_frequency = 22

text_clf_svm = Pipeline([('vect', CountVectorizer(min_df=min_frequency, stop_words='english')), ('tfidf', TfidfTransformer()),('clf-svm', SGDClassifier(loss='hinge', penalty='l2', alpha=1e-03, n_iter=1000, random_state=21))])

text_clf_svm = text_clf_svm.fit(X_train.astype('U'),Y_train.astype('U'))
predicted_svm = text_clf_svm.predict(X_test)
# print the actual accuracy
print "svm accuracy: ", np.mean(predicted_svm == Y_test)

#make the confusion matrix
y_actu = pd.Series(Y_test, name='Actual')
y_pred = pd.Series(predicted_svm, name='Predicted')
df_confusion = pd.crosstab(y_actu, y_pred)

print df_confusion


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

All is good with this as far as im concerned made sure to install all dependencies and module sin the folder from which im running the code. but when I run it I get the following error

'''''
[root@python-political-bias-app fyp]# semodule -i mynginx.pp
[root@python-political-bias-app fyp]# env/bin/uwsgi --socket 127.0.0.1:8080 -w WSGI:app &
[1] 1710
[root@python-political-bias-app fyp]# *** Starting uWSGI 2.0.15 (64bit) on [Wed Feb 7 01:16:21 2018] ***
compiled with version: 4.8.5 20150623 (Red Hat 4.8.5-16) on 06 February 2018 20:03:13
os: Linux-3.10.0-693.17.1.el7.x86_64 #1 SMP Thu Jan 25 20:13:58 UTC 2018
nodename: python-political-bias-app
machine: x86_64
clock source: unix
pcre jit disabled
detected number of CPU cores: 1
current working dir
Oddly unable to reach the media folder

Hello everyone,

I'm tinkering with an image gallery that should connect to user profiles on my page, but I can't seem to make contact with my media folder come upload time, and I'm hoping someone might point me in the right direction.

In settings.py I have:

MEDIA\_ROOT = os.path.join(BASE\_DIR, 'media')

MEDIA\_URL = '/media/'

In my main urls.py file I have:

urlpatterns = [
...
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

and finally in models.py I have:

class Gallery(models.Model):
class Meta:
verbose_name = 'gallery'
verbose_name_plural = 'galleries'
owner = models.ForeignKey(Profile, on_delete=models.CASCADE)
extra_img = models.ImageField(default='default.jpg', upload_to='images')

def __str__(self):
return self.owner.user.username

def save(self, force_insert=False, force_update=False, using=None):
super().save()
#print(settings.MEDIA_URL + 'images/thumbs_color')


/r/django
https://redd.it/a68qax
Live Data Plotting with Matplotlib

Below is a program I am using to read and plot the value of a sensor (simply a potentiometer at the moment). I am using two DIGI XBEE Pro SX Modems to transceive the data. The majority of the code below is provided by DIGI. The program displays the value of the sensor on the screen but when the compiler reaches the plotting section it simply doesn't execute. There are no errors. I am using Python 3.8, jupyter notebook, and anaconda.

\#########################################################################

from digi.xbee.devices import XBeeDevice

from [digi.xbee.io](https://digi.xbee.io) import IOLine, IOMode

&#x200B;

import matplotlib.pyplot as plt

import matplotlib.animation as animation

import time

import re

import csv

import serial

import datetime as dt

import math

%matplotlib notebook

&#x200B;

&#x200B;

\# TODO: Replace with the serial port where your local module is connected to.

PORT = "COM13"

\# TODO: Replace with the baud rate of your local module.

BAUD\_RATE = 9600

&#x200B;

REMOTE\_NODE\_ID = "REMOTE"

&#x200B;

IO\_SAMPLING\_RATE = 1 # 0.5 seconds.

IOLINE\_IN = IOLine.DIO3\_AD3

i=0

&#x200B;

def main():



\#print(" +----------------------------------------------+")

\#print(" | XBee Python Library Handle IO Samples Sample |")

\#print(" +----------------------------------------------+\\n")

&#x200B;

device = XBeeDevice(PORT, BAUD\_RATE)

global i

&#x200B;

try:

[device.open](https://device.open)()

\# Obtain the remote XBee device from the XBee network.

xbee\_network = device.get\_network()

remote\_device = xbee\_network.discover\_device(REMOTE\_NODE\_ID)

if remote\_device is None:

print("Could not find the remote device")

exit(1)

&#x200B;

\# Set the local device as destination address of the remote.

remote\_device.set\_dest\_address(device.get\_64bit\_addr())

&#x200B;

\# Enable periodic sampling every IO\_SAMPLING\_RATE seconds in the remote device.

remote\_device.set\_io\_sampling\_rate(IO\_SAMPLING\_RATE)

&#x200B;

\# Register a

/r/IPython
https://redd.it/bf8dg2
flask error

[main.py](https://main.py)

&#x200B;

data = {'query':'aditya'}
try:
response = requests.post('http://localhost:5000/search',json = data)
except requests.exceptions.Timeout:
print("Time Out")

&#x200B;

&#x200B;

[app.py](https://app.py)

&#x200B;

u/app.route("/search", methods=["GET","POST"])
def search_route():
with sqlite3.connect(DBPATH) as c2:
data = request.get_json(force=True)
#print(data)
d = "%" + data + "%"
with sqlite3.connect(DBPATH) as c2:
res = c2.execute("select * from answers where title like ?", [d])
answers = [{"id": r[0], "title": r[1]} for r in res]
return jsonify(list(answers)), 200

error :

&#x200B;

d = "%" + data + "%"
TypeError: can only concatenate str (not "dict") to str
127.0.0.1 - - [19/Aug/2021 07:04:12] "POST /search HTTP/1.1" 500 -
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>500 Internal Server Error</title>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.</p>

/r/flask
https://redd.it/p7fj2y
Django-filter; creating a variable which is callable from the view

I have a filter which can be used to filter the products on brand(s), which looks like this:

class SortFilter(django_filters.FilterSet):
ORDER_BY_CHOICES = (
('-discount_sort', 'Hoogste korting'),
('-new_price', 'Hoogste prijs'),
('new_price', 'Laagste prijs'),
)
order_by = django_filters.ChoiceFilter(label='Sorteer op', choices=ORDER_BY_CHOICES,
method='filter_by_order',
empty_label=None)

#HERE I WOULD LIKE THIS INPUT A VARIABLE INTO THE QUERYSET variable of the filter
brand = django_filters.ModelMultipleChoiceFilter(queryset=Product.objects
.order_by('brand')
.filter(categorie='eiwitten')
.values_list('brand', flat=True).distinct()
, widget=forms.CheckboxSelectMultiple)
q = django_filters.CharFilter(method='multiple_field_search', widget=TextInput(attrs=
{'placeholder': 'Zoek..'}))


class Meta:
model = Product
fields = ['brand', 'q']


def filter_by_order(self, queryset, name, value):
return queryset.order_by(value)


def multiple_field_search(self, queryset, name, value):
return queryset.filter(
Q(title__icontains=value) | Q(categorie__icontains=value) | Q(brand__icontains=value)
)

&#x200B;

As you can see, the brand filter returns a flat list of all possible brands in the categorie 'eiwitten'. Is there a way to make the queryset in brand a variable which I can input from my view function? This way I can use the filter for every page. Resulting in a unique brand list depending on the categorie. My view function for the 'eiwitten' page looks like this:

def eiwit(request):
#print(request.GET.getlist('brand'))
# filter alleen eiwitproducten

/r/django
https://redd.it/10houtj
Django-filter; creating a variable which I can set from my view function

I have a filter which can be used to filter the products on brand(s), which looks like this:

class SortFilter(django_filters.FilterSet):
ORDER_BY_CHOICES = (
('-discount_sort', 'Hoogste korting'),
('-new_price', 'Hoogste prijs'),
('new_price', 'Laagste prijs'),
)


order_by = django_filters.ChoiceFilter(label='Sorteer op', choices=ORDER_BY_CHOICES,
method='filter_by_order',
empty_label=None)
brand = django_filters.ModelMultipleChoiceFilter(queryset=Product.objects
.order_by('brand')
.filter(categorie='eiwitten')
.values_list('brand', flat=True).distinct()
, widget=forms.CheckboxSelectMultiple)
q = django_filters.CharFilter(method='multiple_field_search', widget=TextInput(attrs=
{'placeholder': 'Zoek..'}))


class Meta:
model = Product
fields = ['brand', 'q']


def filter_by_order(self, queryset, name, value):
return queryset.order_by(value)


def multiple_field_search(self, queryset, name, value):
return queryset.filter(
Q(title__icontains=value) | Q(categorie__icontains=value) |
Q(brand__icontains=value)
)

def eiwit(request):
#print(request.GET.getlist('brand'))
# filter alleen eiwitproducten
eiwit_list = ['eiwitten']
eiwit_filter = Q()
for item in eiwit_list:
eiwit_filter = eiwit_filter | Q(categorie=item)


brand_list = request.GET.getlist('brand')
brand_filter = Q()
for b in brand_list:
brand_filter = brand_filter | Q(brand=b)


products = models.Product.objects.filter(eiwit_filter).filter(brand_filter)
product_amount = len(products)


# sorteer filter
filtered = SortFilter(
request.GET,
queryset=products
)


# paginator
paginator = Paginator(filtered.qs, 12)
page = request.GET.get('page')


/r/djangolearning
https://redd.it/10hov5o
Confused about the delete route in my blueprint

So I'm making a book tracking application based off the flask tutorial with a few extra features (like allowing the user to input their current page and calculating a completion status)

Right now, my delete function is acting funny. The blog delete function takes me to a route
"POST /3/delete HTTP/1.1"
My version returns
"POST /anonymous/to%20be%20deleted/update HTTP/1.1"
Notice how it the url_for function builds the route for update instead?
This is my book.delete function I have in the book blueprint....

@bp.route("/<book_author>/<book_title>/delete", methods=('POST',))
def delete(book_author, book_title):

#updated_book = get_author_book(book_title, book_author)
book_id = returnIdFromTitleAndAuthor(book_title, book_author)

print("book_id currently is: " + book_id['id'])

if book_id is None:
flash("No book of that title + author to delete.")

db = get_db()
db.execute("DELETE FROM books WHERE books.id = ?", (book_id['id'],))
db.commit()

#print("Book is outta here")
flash("Book Deleted")
return redirect(url_for("book.index"))

None of the print statements are showing, meaning the function isn't being called. Here is

/r/flask
https://redd.it/1emtg60
What could I have done better here?

Hi, I'm pretty new to Python, and actual scripting in general, and I just wanted to ask if I could have done anything better here. Any critiques?

import time
import colorama
from colorama import Fore, Style

color = 'WHITE'
colorvar2 = 'WHITE'

#Reset colors
print(Style.RESETALL)

#Get current directory (for debugging)
#print(os.getcwd())

#Startup message
print("Welcome to the ASCII art reader. Please set the path to your ASCII art below.")

#Bold text
print(Style.BRIGHT)

#User-defined file path
path = input(
Fore.BLUE + 'Please input the file path to your ASCII art: ')
color = input('Please input your desired color (default: white): ' + Style.RESET
ALL)

#If no ASCII art path specified
if not path:
print(Fore.RED +

/r/Python
https://redd.it/1p4ffmh