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
How to get friendly Validation Errors

I have the following model and have a nice, friendly validation error message in a custom clean method that works great, it provide a message and a link to follow. However, I also need a custom save method which then causes the validation error to show up as a debug error when I call clean. How would I achieve a friendly validation error here?

FYI: this is an old, old legacy server running django 1.3, python 2.7

class Event(models.Model):
title = models.CharField(max_length=100)
slug = models.CharField(max_length=50, help_text='Automatically built from the title, location and start time.', default="DO NOT EDIT")
location = models.CharField(max_length=50)
event_start_time = models.TimeField()
...
# clean method that will return a friendly error if the slug is not unique and provide a link to list other records with the same slug:
def clean(self, *args, **kwargs):
from django import forms
from django.utils.safestring import mark_safe
while Event.objects.filter(slug=self.slug).exclude(pk=self.pk):
error_message = 'Please double check that your event has not already been entered into the calendar. An event with the exact or very similar title, location and start time already exists.<br /><br /><a href="/admin/events/event/?q=%s">Click here to check existing matching records</a>.' % self.slug
raise forms.ValidationError(mark_safe(error_message))

def save(self):
from django.template.defaultfilters import slugify
self.slug = "%s-%s-%s" % (slugify(self.title)[:39], slugify(self.location), slugify(self.event_start_time)[:4])
self.clean()
return super(Event, self).save()


/r/django
https://redd.it/7psad5
gifmaze: make GIF animations of various maze generation and maze solving algorithms
https://github.com/neozhaoliang/gifmaze

/r/Python
https://redd.it/7puvuh
Created a bot that combines the most popular news images

/r/Python
https://redd.it/7prz39
[AF] Newb question: Can't get Flask-SocketIO and Flask-SSLify to work?

I generated a self-signed certificate using OpenSSL following the procedure found online, saving the certificate and key as "cert.pem" and "key.pem". This is my minimal test case:

from flask import Flask
from flask_socketio import SocketIO
from flask_sslify import SSLify

app = Flask(__name__)
app.secret_key = "secret!"
socketio = SocketIO(app)
SSLify(app)

@app.route("/")
def home():
return "Hello world!"

socketio.run(app, host='0.0.0.0', port=80, certfile='cert.pem', keyfile='key.pem')

Then when I try to visit my site, I get this error:

Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/eventlet/greenpool.py", line 88, in _spawn_n_impl
func(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/eventlet/wsgi.py", line 750, in process_request
proto.__init__(sock, address, self)
File "/usr/lib/python3.5/socketserver.py", line 681, in __init__
self.handle()
File "/usr/lib/python3.5/http/server.py", line 422, in handle
self.handle_one_request()
File "/usr/local/lib/python3.5/dist-packages/eventlet/wsgi.py", line 356, in handle_one_request
self.raw_requestline = self.rfile.readline(self.server.url_length_limit)
File "/usr/lib/python3.5/socket.py", line 575, in readinto
return self._sock.recv_into(b)
File "/usr/local/lib/python3.5/dist-packages/eventlet/green/ssl.py", line 204, in recv_into
return self._base_recv(nbytes, flags, into=True, buffer_=buffer)
File "/usr/local/lib/python3.5/dist-packages/eventlet/green/ssl.py", line 225, in _base_recv
read = self.read(nbytes, buffer_)
File "/usr/local/lib/python3.5/dist-packages/eventlet/green/ssl.py", line 139, in read
super(GreenSSLSocket, self).read, *args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/eventlet/green/ssl.py", line 113, in _call_trampolining
return func(*a, **kw)
File "/usr/lib/python3.5/ssl.py", line 791, in read
return self._sslobj.read(len, buffer)
File "/usr/lib/python3.5/ssl.py", line 575, in read
v = self._sslobj.read(len, buffer)
ssl.SSLError: [SSL: HTTP_REQUEST] http request (_ssl.c:1977)

Am I missing something basic here? A configuration setting? Or am I using the extensions wrong? SSLify is supposed to automatically redirect HTTP requests to HTTPS, right? I tried googling a bit, but it looked like I was doing everything according to the instructions...

(If it matters, Flask-SocketIO is running on eventlet, which worked fine before adding SSL)

/r/flask
https://redd.it/7pue5g
[AF] Odd Syntax Error when trying to deploy app with apache and mod_wsgi

I’m learning about deploying flask apps using apache2.4 and mod_wsgi on an Unbuntu 16.04 server by building the simplest of ‘Hello, Word!’ apps, but I encountered a weird syntax error related to my wsgi file and I’m stumped.

Apache seems to be running fine but when I hit the app’s domain, I get apache’s standard 500 error and the logs list the following:

[wsgi:error] [pid 28427:tid 140540431517440] mod_wsgi (pid=28427): Target WSGI script '/var/www/myapp.domain.com/myapp.wsgi' cannot be loaded as Python module.
[wsgi:error] [pid 28427:tid 140540431517440] mod_wsgi (pid=28427): Exception occurred processing WSGI script '/var/www/myapp.domain.com/myapp.wsgi'.
[wsgi:error] [pid 28427:tid 140540431517440] Traceback (most recent call last):
[wsgi:error] [pid 28427:tid 140540431517440] File "/var/www/myapp.domain.com/myapp.wsgi", line 5, in <module>
[wsgi:error] [pid 28427:tid 140540431517440] exec(file_.read(), dict(__file__=activate_this))
[wsgi:error] [pid 28427:tid 140540431517440] File "<string>", line 4
[wsgi:error] [pid 28427:tid 140540431517440] deactivate () {
[wsgi:error] [pid 28427:tid 140540431517440] ^
[wsgi:error] [pid 28427:tid 140540431517440] SyntaxError: invalid syntax

The syntax error referenced in the logs are pointing to code in my virtual environment’s activation script located at ./venv/bin/activate

I’m wondering if my use the venv module vs. virtualenv is causing this issue

Here is the content of my app’s wsgi file (test is the name of the module were flask is instantiated):

#!/usr/bin/python3
activate_this = '/var/www/myapp.domain.com/venv/bin/activate'
with open(activate_this) as file_:
exec(file_.read(), dict(__file__=activate_this))

import sys
sys.path.insert(0, '/var/www/myapp.domain.com')

from test import app as application

Any guidance would be most appreciated.



/r/flask
https://redd.it/7pstd5
Python in 3D game development?

I am learning python on codecademy (Stop laughing for a second, I only knew some rookie level of HTML+CSS, I am honestly really impressed after spent a night on codecademy. Now I am able to read some stuff on github that was total alien to me.)

Now after some researches, most evidences convinced me that python is ..the least ideal language in game making sector for various reasons. But anyway it is *almost* non-existent in the industry, yeah I am aware that eve and some other was written in python. However, I also knew that there some outdated plugins and Panda3D could be used for games and also unreal engine community seem to have a ongoing plugin that allow user to give command in python.

My end goal of learning python is game prototyping. I wanted to be a game designer and came from media-art background doesn't seem to help much in job seeking. So I decided to learn python so I could prototype some stuff for portfolio purpose. I stalked on panda3D forum for a while, definitely saw some impressive things. On the other hand, the community seems only at hobbyist level which have me worried. If I go on apply for jobs, will python-based portfolio get rejected given that I am not willing to learn c++? (who has lifespan for that???)

/r/Python
https://redd.it/7pwniu
[AF] How should two Flask websites run together on an Ubuntu server?

I have two Flask websites. One of them is a link-shortener and the other is a simple web file browser. I want them both to run on the same Ubuntu server. What would be a good, easy way to do this?

Specifically, the link-shortener ([ovipositor](https://github.com/wdbm/ovipositor)) saves to a database file and the web file browser ([a fork of browsepy](https://github.com/wdbm/browsepy)) can display file listings at some shared directory. They are for production (so should be someway secure) but I'm not worried about performance.

/r/flask
https://redd.it/7ps58l
I am using a google maps module that generates a "map.html" in /templates/ depending on what the user searches for but map.html only reflects the first search a user does for some reason and wont change with subsequent searches.

I know this is convoluted, but here we go. I made a super schematic version of what I am doing here:

https://pastebin.com/TunjvUi0

The map_maker module creates map.html based on user input and puts it in the templates folder. The first time the user gives input the map is rendered perfectly. The strange thing is that each subsequent user search only shows the first map even though the input is changing and I can see the new searches overwriting the first map in the templates folder with a new map. So I know my module is working correctly, there is something about flask that only remembers the first map I made. Please help :(

EDIT: I already found it was a configuration: app.config['TEMPLATES_AUTO_RELOAD'] = True
This is needed to update the template from the disk with each search the way I understand it.

/r/flask
https://redd.it/7q2tk1
Flask Issue - Running wrong version of Python

I'm not sure how to get my flask to run with version 3.6. When apache loads the wsgi file it keeps loading with 2.7.

I've used a virtual env and added the code:

activate_this = '/var/www/FlaskApp/FlaskApp/venv/bin/activate_this.py'
with open(activate_this) as file_:
exec(file_.read(), dict(__file__=activate_this))

The above doesn't fix anything. Is there another way I can get the wsgi file to load with a venv or default the system wide python to use 3.6?

/r/flask
https://redd.it/7pqwx5