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
[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
Computing S-value from R-squared for SVM?

I split a dataset consisting of 3 columns for `X` and 1 column for `y`.

X_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, test_size=0.25)

I then a support vector regression model to generate predictions

clf = svm.SVR(kernel='linear')
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)

I then computed the R-squared value

r2_score(y_pred, y_test)

How do I then compute the S-value? Is it just `stdev(y_pred)*sqrt(1-R^2)`

/r/pystats
https://redd.it/6vc06t
How can I enable file path autocompletion in the IPython console in PyCharm?

(No sure this is the appropriate place to ask this question - but I find no better one. I did ask of it on StackOverflow.)

Path autocompletion in the IPython console in PyCharm does not work well:

c:/U<TAB>
should autocomplete to:

cd c:/Users/

on my machine; instead, the best it manages is:

cd c:/UserWarning

which is plain wrong. IPython in the Anaconda prompt, however, behaves as it should.

My strong assumption is that this is due to PyCharm not using the standard IPython configuration files.

I'm aware of the console starting script ins PyCharm:

Settings->Build, Execution, Deployment->Console->Python console
and I've successfully used it to activate a simple magic command I've written.

So here my question: is there a code configuration snippet that could be inserted there, and that could just enable file path autocompletion? Or a pointer to a general description on how IPython configuration files "work", that would enable me to figure it out myself? That is, I imagine, the most doable hack that would solve the problem for the time being.

Alternatively, any experiences with writing your own autocompletion using the following libraries:

IPython.core.completer
IPython.core.completerlib
?

Is that doable? How much work can that be?

Thanks in advance!

Links supporting claims in the question(s) above:

1) Autocompletion in IPython console in PyCharm not working as it should

On StackOverflow there are three questions with similar wording, but not one substantial answer:

https://stackoverflow.com/questions/32542289/pycharm-ipython-tab-completion-not-working-within-python-console
https://stackoverflow.com/questions/35612338/how-to-set-ipython-profile-in-pycharm
https://stackoverflow.com/questions/32458158/pycharm-python-console-autocompletion

(No, using Ctrl+Space instead of Tab does not solve anything.)

JetBrains (creators of PyCharm) know about this since, at least, two years:

https://intellij-support.jetbrains.com/hc/en-us/community/posts/205820389-Console-tab-completion-

and seems to have started working on it, but never finished it. Discussion states " this is only the initial step to getting full IPython tab completions": https://youtrack.jetbrains.com/issue/PY-9345 . But the issue is closed since October 2016: https://github.com/JetBrains/intellij-community/pull/440

2) PyCharm not using ipython_config.py to configure IPython Console:

https://intellij-support.jetbrains.com/hc/en-us/community/posts/206603035-Which-ipython-config-py-is-used-to-configure-IPython-for-Python-Console-

My setup:
PyCharm Community Edition 2017.2.1
Anaconda 2 (Python 2.7), version 4.3.22
which contains
IPython 5.1.0
on Windows 7 Professional N

/r/IPython
https://redd.it/6vanpr
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/6vb9c5
For my first Django project, I created a site to help you find quality Software Development / CS books!

Hey guys, as my first Django project I created a website that scrapes data from Reddit, aggregates, categorises and ranks every book mentioned each day based on the karma of the author, upvotes received by the comment and some other factors.

You can check it out here: http://reddittopbooks.com.

Getting up to speed with Django with a fair bit of Python experience took me around 2 days, I mainly used to official tutorial as a starting point. Check out the about section for more info on the site!

/r/django
https://redd.it/6vckcz