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
Django-page-cms gets official inline page editing support
http://django-page-cms.readthedocs.io/en/latest/edit-content.html

/r/django
https://redd.it/5jl3ej
[AF] Flask Admin not displaying Foreign Key column

I'm building a blog with Flask. I use Flask-Admin for setting up an administrative interface. Everything is fine, but I cannot see the "tags" field in the Post form. This is defined as a relationship/FK in my Post model.

Please see below my model file and admin configuration. Appreciate any idea.

Thanks!

##### MODELS.PY
tags = db.Table('post_tag',
db.Column('tag_id', db.Integer, db.ForeignKey('tag.id')),
db.Column('post_id', db.Integer, db.ForeignKey('post.id'))
)


class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
date = db.Column(db.DateTime, default=datetime.utcnow)
title = db.Column(db.String(140))
slug = db.Column(db.String(200))
content = db.Column(db.Text)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
_tags = db.relationship('Tag', secondary=tags,
backref=db.backref('posts', lazy='dynamic'))

@observes('title')
def compute_slug(self, title):
self.slug = re.sub('[^\w]+', '-', title.lower())

@staticmethod
def newest(num):
return Post.query.order_by(desc(Post.date)).limit(num)

@property
def tags(self):
return ",".join([t.name for t in self._tags])

@tags.setter
def tags(self, string):
if string:
self._tags = [Tag.get_or_create(name) for name in string.split(',')]

def __repr__(self):
return "<Post '{}': '{}'>".format(self.title,self.date)


class Tag(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(25), nullable=False, unique=True, index=True)

@staticmethod
def get_or_create(name):
try:
return Tag.query.filter_by(name=name).one()
except:
return Tag(name=name)

@staticmethod
def all():
return Tag.query.all()
def __str__(self):
return self.name

def __repr__(self):
return self.name



##ADMIN.PY
admin = Admin(app, name='Admin', template_mode='bootstrap3')

class CKTextAreaWidget(TextArea):
def __call__(self, field, **kwargs):
if kwargs.get('class'):
kwargs['class'] += ' ckeditor'
else:
kwargs.setdefault('class', 'ckeditor')
return super(CKTextAreaWidget, self).__call__(field, **kwargs)

class CKTextAreaField(TextAreaField):
widget = CKTextAreaWidget()

class PostAdmin(sqla.ModelView):
form_overrides = dict(content=CKTextAreaField)
create_template = 'blog/ckeditor.html'
edit_template = 'blog/ckeditor.html'
form_excluded_columns = ('slug')
def is_accessible(self):
return current_user.is_authenticated
admin.add_view(PostAdmin(Post, db.session))

class TagAdmin(sqla.ModelView):
def is_accessible(self):
return current_user.is_authenticated
admin.add_view(TagAdmin(Tag, db.session))

class UserAdmin(sqla.ModelView):
def is_accessible(self):
return current_user.is_authenticated
admin.add_view(UserAdmin(User, db.session))

/r/flask
https://redd.it/5dbvbi
How to authenticate IMAP using oauth tokens?

I'm building a flask app that authenticates a user using Google's OAuth and then connects to gmail using IMAP for further email processing, however, i'm having trouble with the whole process.

My current code is as follows. I'm able to sign the user into google and access their user information, such as their email, and obtain an access token, however, i'm not sure where to go from there. Any/all help is greatly appreciated.

from flask import Flask, request, url_for, session, redirect, jsonify
from flask_oauth import OAuth
import json
import imaplib
import email
from bs4 import BeautifulSoup



GOOGLE_CLIENT_ID = 'MY ID'
GOOGLE_CLIENT_SECRET = 'MY SECRET'
REDIRECT_URI = '/authorized' # one of the Redirect URIs from Google APIs console

SECRET_KEY = 'Uber'
DEBUG = True

app = Flask(__name__)
app.secret_key = 'Uber'
oauth = OAuth()

google = oauth.remote_app('google',
base_url='https://www.google.com/accounts/',
authorize_url='https://accounts.google.com/o/oauth2/auth',
request_token_url=None,
request_token_params={'scope': 'https://www.googleapis.com/auth/userinfo.email',
'response_type': 'code'},
access_token_url='https://accounts.google.com/o/oauth2/token',
access_token_method='POST',
access_token_params={'grant_type': 'authorization_code'},
consumer_key=GOOGLE_CLIENT_ID,
consumer_secret=GOOGLE_CLIENT_SECRET)


@app.route('/')
def index():
access_token = session.get('access_token')
if access_token is None:
return redirect(url_for('login'))

access_token = access_token[0]
from urllib2 import Request, urlopen, URLError

headers = {'Authorization': 'OAuth '+access_token}
req = Request('https://www.googleapis.com/oauth2/v1/userinfo',
None, headers)
try:
res = urlopen(req)
except URLError, e:
if e.code == 401:
# Unauthorized - bad token
session.pop('access_token', None)
return redirect(url_for('login'))
return res.read()
j = json.loads(res.read())
email_address = j['email']
print email_address, access_token
return "Hello World"


@app.route('/login')
def login():
callback=url_for('authorized', _external=True)
return google.authorize(callback=callback)



@app.route(REDIRECT_URI)
@google.authorized_handler
def authorized(resp):
access_token = resp['access_token']
session['access_token'] = access_token, ''
return redirect(url_for('index'))


@google.tokengetter
def get_access_token():
return session.get('access_token')

def Uber_Cost(email_address, access_token):

# this function is completed, i'm just not sure how to authenticate IMAP using the oauth from above

/r/flask
https://redd.it/5dc81w
YuleLog - A terminal based Yule Log Fireplace for the Christmas Season. Made with Asciimatics!

I had the idea this morning to make a terminal based fireplace like the ones you see on youtube around this time of year. I looked around and didn't really see anything like it so I figured I'd go ahead with it.

I have always loved Asciimatics and remembered there's an awesome fire effect built in. There was a Christmas example, but it only had floating text.

I then found a photo of a log and converted it with https://picascii.com/ and spent some time tweaking the position a bit till it looked good on different console sizes.

It's up on Pypi so you can

`$ pip install YuleLog`

Not a lot of work at all but I'm pretty happy with the outcome and I hope you all are too :D

tl;dr - YuleLog -

Screenshot: https://github.com/Duroktar/YuleLog/blob/master/yule_log/screenshot.png

Github - https://github.com/Duroktar/YuleLog

Pypi - https://pypi.python.org/pypi

Release page - https://github.com/Duroktar/YuleLog/releases/tag/0.0.1

Love, Peace and Happiness to you all. Merry Christmas!!

edit: WORKS BEST IN FULLSCREEN!

/r/Python
https://redd.it/5k5o9l
Basic Model concept but I can't wrap my head around how to do it... Help, please.

Spending part of the Christmas holiday working on my first big Django project and I've hit a wall. I just can't wrap my head around how to do this so any help would be appreciated.

Custom user account (already made and set up) has a field which is used to reference an external API. Information related to the user (transaction list with details) is pulled from the external API (JSON) and saved to my database. Each user will have multiple transactions and each transaction will have multiple pieces of data associated with it that needs to be saved (to be later presented as a graph).

I can't wrap my head around how to set up the model to get the JSON data into my database. This includes creating the model and saving it.

I realize it's probably an elementary problem but if anyone can just list what I need to do to get this done I'd appreciate it. Most tutorials use data from forms (or blog entries) to illustrate how to save data to a database so I guess I need to know how to process and save data from a non-form outside source.

/r/django
https://redd.it/5k45xh
I implemented a module in python for oversampling skewed datasets. Would love to hear your thoughts on it!

It is an implementation of the ADASYN algorithm (link to paper: bit.ly/22KgAnP) and is designed to work along the scikit-learn API. I ran into the need of an oversampling module that focuses more on examples that are harder to classify, and I said, what the heck... I will implement it on my own. Feel free to use it in your projects and if you find any bugs just open an issue

https://github.com/stavskal/ADASYN

Don't forget to star if you find it useful ;)

/r/pystats
https://redd.it/44r9ye
Supervisord project: Python 2 to 3 porting help needed

Supervisor is a process supervisor used by hundreds of thousands (millions?) of production systems. It is used by people who don't even use Python as their application language.

supervisord is one of the most useful tools to run production systems.. and is more relevant when we look at the Docker world..Where is it is usually run as "init 1".

For us (and a crazy ton of systems people who dont even use python for application code), the "supervisor" incompatibility is a blocker to move to py3.

Unfortunately, I think the maintainers are handicapped by py3 expertise - https://github.com/Supervisor/supervisor/labels/python%203

>Supervisor has some major issues on Python 3. Many of these issues are encoding related as well so merging this one patch doesn't move the needle much. We need someone who has strong experience in Python 2/3 porting and is willing to spend a non-trivial amount of time looking at these bytes/strings issues together.


https://github.com/Supervisor/supervisor/pull/471#issuecomment-267793117

/r/Python
https://redd.it/5k1875
a Py3.6 fizzBuzz oneliner with f-strings

print(*map(lambda i: f"{'Fizz' * (not i%3)}{'Buzz' * (not i%5)}" or i, range(1,101)), sep='\n')



/r/Python
https://redd.it/5k7lnb
How to build an interactive dashboard?

Do any packages exist allowing a dashboard with greater layout flexibility than the notebook allows?

/r/IPython
https://redd.it/4ogcgg