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
flask-allows 0.3.1 released

https://pypi.org/project/flask-allows/

flask-allows is an authorization toolkit along the lines of DRF's permissions and the extension to that called rest conditional (which allows modifying permissions with and/or/not).

It supports loading identities from whatever manager you use, as well as explicitly providing them when the permission is checked in most instances.

It's also configurable as to what exception unfulfilled requirements throw. By default it's werkzeug's Forbidden.

The main conceit is the concept of a Requirement. A Requirement may be a simple permission check or more complicated like "Is this object owned by the current user, or does the current user has access rights to it anyways?"

A Requirement can either be an implementation of the abstract Requirement class, or any callable that accepts the current user and request and returns a boolean.

The actual extension class provides a `fulfill` method which accepts requirements and optionally an explicit identity and sees if the identity meets the requirements. `fulfill` returns a boolean.

There is also a decorator form called `requires` that only accepts requirements and defers to the identity loader. On a failure, it throws the configured exception.

Built on that are helpers like a standalone requires decorator and the Permission class. The decorator defers to the Permission class.

Permission accepts any number of requirements and needs an active application context and the extension to be loaded to instantiate. Optionally, it can accept an identity or an exception to throw, otherwise it defers to the currently loaded app's extension.

Once created, it can be used as either a boolean or a context manager.

When used as a boolean, it simply returns if the provided requirements are met. If used as a context manager, it'll throw immediately if the requirements aren't met.

Happy to answer any questions.

Preemptively: Why not Flask Principal? Principal seems to be unmaintained, with no commits in two years and no activity on the issues or pull requests on the repo.

Additionally, Flask Principal takes a different view of authorization. In Principal, Identities are expected to explicitly enumerate their claims. With Allows, the onus is on Requirements to verify.

The Principal route works well until you need to load hundreds of a claims into memory on each request, it also forces you to move permissioning code inside the route handler for dynamic cases - does this user own this resource? Which is jarring to me.

/r/flask
https://redd.it/6uy1sn
[AF] Splinter with flask: checking if element/site is loaded, not working

So this is the method i use to check if an element is loaded and then continue only when the element is loaded.

loadingbot = browser.is_element_present_by_xpath('//*[@id="inventory_bot"]/div[1]')

while loadingbot == False:
print(loadingbot)
loadingbot = browser.is_element_present_by_xpath('//*[@id="inventory_bot"]/div[1]')
time.sleep(0.1)

When i run this script with chrome it everything works great, but when i switch to flask it just gets stuck on that and keeps printing "False".
How to fix this? or is this a "bad programming practice" anyway and i should do something else to check if an element is loaded?

/r/flask
https://redd.it/6unz6y
The more I learn about Python, the more I realized I am practically only using it as a wrapper around libraries written in Fortran, C, ... How have Python become *the* wrapper everybody uses?

The why is understandable: Python is easy. Gluing all those libraries together, and make them readily available is very desirable.

Python is not the only language that does what it does. It is the most popular, though.

What I am interested in understanding is the history of this actually happening. Why Python, and not any other scripting language?

/r/Python
https://redd.it/6v0amj
[P] Line-by-line Preprocessing Walkthrough for grt123's winning Data Science Bowl Submission

I'm currently going through grt123's [winning implementation](https://github.com/lfz/DSB2017/) for lung cancer detection to build a similar model. As I do this, I'm going line by line to understand exactly what they're doing with the data at every step.Their preprocessing in particular is extremely impressive and robust to edge-cases. It's full of image manipulation tricks that are useful to keep in your back pocket.

I've put together an [educational notebook](http://nbviewer.jupyter.org/github/bckenstler/dsb17-walkthrough/blob/master/Part%201.%20DSB17%20Preprocessing.ipynb) that explains each line (to the best of my knowledge), including before/after visualizations. My hope is that this will be useful to anyone either trying to understand what they did, or who want to adapt what they did to a similar dataset / task.

/r/MachineLearning
https://redd.it/6uyg5t
[R] The Microsoft 2017 Conversational Speech Recognition System
https://www.microsoft.com/en-us/research/wp-content/uploads/2017/08/ms_swbd17-2.pdf

/r/MachineLearning
https://redd.it/6v0yih
[Ask Flask] [Flask-SQLAlchemy] [Flask-RESTful] Is it possible to implicitly define a model's column? Want to permit POST requests with *args parameter. Can SQLAlchemy dynamically generate columns?

Hi r/Flask!

I'm creating a RESTful API that returns a list of cocktail ideas based on an input of ingredients. Right now I'm trying to figure out how to store multiple ingredients per row.

Here's my Cocktail resource class. Looking for advice. I thought about creating a separate table for ingredients, but how would I relate that back to the Cocktail table? Foreign key? Little lost here!

Thanks!

from flask_restful import Resource, reqparse
from flask_jwt import jwt_required
from models.cocktail import CocktailModel, IngredientModel

class Cocktail(Resource):
parser = reqparse.RequestParser()
parser.add_argument('name',
type=str,
required=True,
help="This field cannot be left blank")
parser.add_argument('instructions',
type=str,
required=True
help="This field cannot be left blank")
parser.add_argument('ingredients', action='append',
type=str,
required=True,
help="This field cannot be left blank")

def get(self, *ingredients):
#GET json of drinks based on ingredient args

@jwt_required()
def post(self, name, instructions, *ingredients):
# CREATE a drink
# add check if drink already exists

data = Cocktail.parser.parse_args()

cocktail = CocktailModel(name, data['ingredients'],
data['instructions'], data['ingredients'])
try:
cocktail.save_to_db()

except:
return {"message": "An error occured inserting the item."}, 500

return item.json(), 201




/r/flask
https://redd.it/6uke6q
[AF] redirect all non-www to www with heroku, code seems to work, but SEO tool says its wrong

I am using following code to redirect all content to www:

@app.before_request
def redirect_nonwww():
"""Redirect non-www requests to www."""
urlparts = urlparse(request.url)
if urlparts.netloc == 'path-of-exile-builds.com':
urlparts_list = list(urlparts)
urlparts_list[1] = 'www.path-of-exile-builds.com'
return redirect(urlunparse(urlparts_list), code=301)

My site os path-of-exile-builds.com and I want all content to go to www and also to optimize my site to be as fast as possible, but this:
https://sitechecker.pro/https://www.path-of-exile-builds.com/

tells me that it is not working eventhough if I type it without www it redirects to www, I already used this tool a few times and it was always correct, so I am confused whats wrong here.

/r/flask
https://redd.it/6v47tt
I built a To-do app with a python backend. Here's the entire code, released under an MIT license. Feel free to self host or fork it to your hearts content

I built this todo app mainly as an experiment to learn javascript, web development and back end Python work. I got it to a stage where I felt like giving selling it a go, lets just say it gently failed (Hindenburg style crashed and burned). Since I don't have much use for it, here's the entire source code, under an MIT license. I'm not even going to pretend the code is any good, but hey, maybe others can learn from my mistakes, eh? Have fun!

https://github.com/oliverb123/cuntoir

If anyone has any questions/suggestions, post them or pm me. Also it's currently running at https://cuntoir.com, but that's gonna go away very soon, basically once my free amazon hosting goes away.

/r/Python
https://redd.it/6v3yzj
[AF] Insert data in PyMongo from api

Hello, maybe you could give me hints where to look...I'm getting information about tv show and movies from TMDB api.

My question is from my search field when a movie or tv show is selected can I insert full information in PyMongo? Right now i can't add more than one information at time like 'title' from this code "series.insert({'title' : request.form.getlist('addSeries')})"

Sorry for my english and my code i'm learning xD.


Here is my code

from flask import Flask, render_template, url_for, request, session, redirect
from flask_pymongo import PyMongo
import bcrypt, json, requests


def create_app():
app = Flask(__name__)

app.config['MONGO_DBNAME'] = 'DBNAME'
app.config['MONGO_URI'] = 'URI'

mongo = PyMongo(app)

# Main (index) route --
@app.route('/')
def index():
if 'username' in session:
return render_template('home.html')

return render_template('index.html')

# Login route --
@app.route('/login', methods=['POST'])
def login():
users = mongo.db.users
login_user = users.find_one({'name' : request.form['username']})

if login_user:
if bcrypt.hashpw(request.form['pass'].encode('utf-8'), login_user['password']) == login_user['password']:
session['username'] = request.form['username']
return redirect(url_for('index'))

return 'Invalid username/password combination'

# Register route --
@app.route('/register', methods=['POST', 'GET'])
def register():
if request.method == 'POST':
# Store user and password
users = mongo.db.users
existing_user = users.find_one({'name' : request.form['username']})

if existing_user is None:
hashpass = bcrypt.hashpw(request.form['pass'].encode('utf-8'), bcrypt.gensalt())
users.insert({'name' : request.form['username'], 'password' : hashpass})
session['username'] = request.form['username']
return redirect(url_for('index'))

return 'That username already exists!'

return render_template('register.html')

@app.route('/logout')
def logout():
# remove the username from the session if it's there
if 'username' not in session:
return redirect(url_for('index'))

session.pop('username', None)
return redirect(url_for('index'))



@app.route('/search', methods=['POST'])
def search():
search = request.form['search']
api = ""
payload = {''}
r = requests.get('https://api.themoviedb.org/3/search/tv?api_key={}'.format(api) + '&language=fr-FR' + '&query={}'.format(search))
json_data = r.json()
results = json_data['results']


return render_template('search.html', idSeries=results)


# Add series to MongoDB
@app.route('/add', methods=['GET','POST'])
def addSeries():
if request.method == 'POST':
series = mongo.db.series
series.insert({'title' : request.form.getlist('addSeries')})

return render_template('home.html')

return 'Erreur'

@app.route('/home')
def home():
if 'username' in session:

series = mongo.db.series
mySeries = series.find()

return render_template('home.html', mySeries=mySeries)

return render_template('index.html')

return app










/r/flask
https://redd.it/6r2b48
Question on how to structure project with React

So from my understanding, a typical flask project has the structure of:

templates directory

static directory (for css, js, image files, etc.)

*.py files for application logic

app.py file for handling routing


How should I structure my app to integrate React into, if I wanted to create separate js files for each component. I've seen some examples use a src folder as the root folder for all the js files. Would this ultimately live in then static directory?


/r/flask
https://redd.it/6qytfc
Serving files

Hello guys i have a .zip file that i would like to serve client side but that .zip file is not in static folder what is the best secure way to send the path of that file to client side. I would appreciate whatever suggestion.

/r/flask
https://redd.it/6r0y9k
DjangoCon help Update

Hello everyone!

You may remember I posted here a [about a month ago](https://www.reddit.com/r/django/comments/6fl9ml/hello_im_speaking_at_djangocon_this_year_and_want/) asking for your opinion on what I should do in my [DjangoCon talk](https://www.reddit.com/r/djangolearning/comments/6fldjh/hello_im_speaking_at_djangocon_this_year_and_want/). Well I am happy to say I collected a ton of information and opinions from everyone, and I wanted to thank the community as a whole for making my talk so successful!

A few different people had asked if the talk would be posted online at a later date, at the time I was unsure of this myself as DjangoCon has done some tutorials in the past, but not always. I found out this week that they will not be posting my tutorial (or any of the 2017 tutorials) this year. Rest assured that all of the talks will be posted as normal though!

---

Regardless the tutorial was a huge success and many of the people who came were incredibly happy to have a more detailed look at Django, instead of the usual "copy/paste this code and type this command" that some talks and tutorials provide. I have been asked by multiple different attendee's if I would be willing to release my slides and code (which I will be doing in a few days), however the largest part of the tutorial was a live coding and q/a section. This cannot really be replicated with a github repo. Instead I want to try and do the next best thing. Over the next few weeks I plan on release a series of blog posts (2 a week) called "0-100 in Django." These blog posts will cover everything I covered in the tutorial. It will be an indepth look at the polls tutorial, that goes even further than the DjangoProject website takes it.

We will talk about Models, Managers, Querysets, Migrations, CBV vs Functional Views, and even best practices for code. We will also add user authentication, unit testing, and so much more!

So if you were one of the people who wanted to go to DjangoCon, but just couldn't afford it please come by! The [first post is already available](https://medium.com/@jeremytiki/0-100-in-django-introduction-75a182637462), and number 2 will be up Monday and cover setting up the best Django environment possible.

/r/djangolearning
https://redd.it/6uln2q