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
[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
Auto populating modified_by and created_by fields

In addition to tracking created_at and modified_at, I'd like to log the created_by and modified_by user (I'm using Flask-Login). Is there a nice way to do this? I'm having a hell of a time figuring out how to do it automatically in the model.

My current solution is to catch the user in the view and set the variable that way, but it feels wrong. I don't know how to access current_user from the model, and can't find any documentation on how to do this. It seems like it should be a pretty normal design pattern.

Any hints would be super helpful. I'm not looking for code, just any ideas of how to do this more cleanly.

Thanks,

Mark

/r/flask
https://redd.it/6vdpzi
How to include scraper as part of django project

I am making a site that will require a scraper to run continuously and watch for changes on an api.

Once a change occurs, it needs to get the change, and push it to a database which is defined by a django model. I am not sure how i can create this structure. Should the scraper be part of django somehow? Should it be a micro service somewhere, but then how do I use djangos ORM to get the models and save them down.

Can anyone point me in the right direction for this?

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