[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
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
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
reddit
Question on how to structure project with React • r/flask
So from my understanding, a typical flask project has the structure of: templates directory static directory (for css, js, image files,...
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
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
reddit
Serving files • r/flask
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...
Using SQLAlchemy with Flask to Connect to PostgreSQL
http://vsupalov.com/flask-sqlalchemy-postgres/
/r/flask
https://redd.it/6qy0k4
http://vsupalov.com/flask-sqlalchemy-postgres/
/r/flask
https://redd.it/6qy0k4
vsupalov.com
Using SQLAlchemy with Flask to Connect to PostgreSQL
Connecting to PostgreSQL from a Flask app, and defining models.
The simple way to understand Django models
https://arevej.me/django-models/
/r/django
https://redd.it/6v4qq9
https://arevej.me/django-models/
/r/django
https://redd.it/6v4qq9
reddit
The simple way to understand Django models • r/django
15 points and 1 comments so far on reddit
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
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
reddit
Hello! I'm speaking at DjangoCon this year and want... • r/django
Good morning everyone! I was selected to speak at DjangoCon this year for the talk "Going from 0-100 with Django". It is going to be a 3-3.5 hour...
Typogrify is a collection of Django template filters that help prettify your web typography by preventing ugly quotes and widows and providing CSS hooks to style some special cases.
https://github.com/chrisdrackett/django-typogrify
/r/django
https://redd.it/6val5b
https://github.com/chrisdrackett/django-typogrify
/r/django
https://redd.it/6val5b
GitHub
GitHub - chrisdrackett/django-typogrify: Typogrify is a collection of Django template filters that help prettify your web typography…
Typogrify is a collection of Django template filters that help prettify your web typography by preventing ugly quotes and widows and providing CSS hooks to style some special cases. - GitHub - chri...
A Tale of Two Python Kafka Clients
https://blog.datasyndrome.com/a-tale-of-two-kafka-clients-c613efab49df
/r/pystats
https://redd.it/6v6vaw
https://blog.datasyndrome.com/a-tale-of-two-kafka-clients-c613efab49df
/r/pystats
https://redd.it/6v6vaw
Medium
A Tale of Two Kafka Clients
We use and love Kafka at Data Syndrome. It enables us to move processing from batch to realtime with minimal pain and complexity. However…
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
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
reddit
Computing S-value from R-squared for SVM? • r/pystats
I split a dataset consisting of 3 columns for `X` and 1 column for `y`. X_train, X_test, y_train, y_test =...
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
(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
Stackoverflow
Pycharm IPython tab completion not working (within python console)
So I have searched high and low for an answer regarding this and I am starting to come to the conclusion that it simply isn't a feature for Pycharm.
I am using IPython in Pycharm and I cannot ge...
I am using IPython in Pycharm and I cannot ge...
COUNTLESS — High Performance 2x Downsampling of Labeled Images Using Python and Numpy
https://medium.com/towards-data-science/countless-high-performance-2x-downsampling-of-labeled-images-using-python-and-numpy-e70ad3275589
/r/pystats
https://redd.it/6vds8q
https://medium.com/towards-data-science/countless-high-performance-2x-downsampling-of-labeled-images-using-python-and-numpy-e70ad3275589
/r/pystats
https://redd.it/6vds8q
Medium
COUNTLESS — High Performance 2x Downsampling of Labeled Images Using Python and Numpy
Downsample labeled segmentations by taking the mode of 2x2 blocks using only Python and numpy. This was first used in a pipeline for generating MIP levels on AI segmentations of brain tissue.
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
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
reddit
What's everyone working on this week? • r/Python
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...
Library which provide mock data for any purpose. From cryptographical data to personal data.
https://github.com/lk-geimfari/mimesis
/r/Python
https://redd.it/6vb4n0
https://github.com/lk-geimfari/mimesis
/r/Python
https://redd.it/6vb4n0
GitHub
GitHub - lk-geimfari/mimesis: Mimesis is a fast Python library for generating fake data in multiple languages.
Mimesis is a fast Python library for generating fake data in multiple languages. - lk-geimfari/mimesis
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
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
Reddittopbooks
Reddit Top Books
Weekly toplist of the most mentioned books across various subreddits, categorized.
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
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
reddit
Auto populating modified_by and created_by fields • r/flask
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...
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
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
reddit
How to include scraper as part of django project • r/django
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...
Hey /r/Python! I made a weird game about simulating evolution of intelligence in PyGame. Tell me what you think!
https://www.youtube.com/watch?v=2boI6R0Gx8A
/r/Python
https://redd.it/6vdaiv
https://www.youtube.com/watch?v=2boI6R0Gx8A
/r/Python
https://redd.it/6vdaiv
YouTube
Critter Evolution - A game for bored nerds
Subscribe for more robotics/software projects!
I made an evolutionary game where the brains of critters get smarter over time. The critters live, mate, eat, hunt, scavenge, sleep, and die. When they mate, their decision-making process is put into the child…
I made an evolutionary game where the brains of critters get smarter over time. The critters live, mate, eat, hunt, scavenge, sleep, and die. When they mate, their decision-making process is put into the child…