Can anyone help me and copy the stylesheet/subcategories-thing from /r/askscience to my subreddit r/kitricks?
I don't know the 101 of how to do it and it would be cool to have subcategories by colors for easy picking.
you can be admin. it's gonna be f cool when it will be fille up!
/r/Python
https://redd.it/5jwp2s
I don't know the 101 of how to do it and it would be cool to have subcategories by colors for easy picking.
you can be admin. it's gonna be f cool when it will be fille up!
/r/Python
https://redd.it/5jwp2s
reddit
Can anyone help me and copy the... • /r/Python
I don't know the 101 of how to do it and it would be cool to have subcategories by colors for easy picking. you can be admin. it's gonna be f...
Creating a CallbackURL to consume a Webhook POST Request (Update and Thanks!)
Hi guys,
A few weeks ago I asked a question about creating a callback url for a webhook [(Original Post Here)](https://www.reddit.com/r/django/comments/5ftsy6/how_do_i_create_a_callback_url_to_consume_a/) and I wanted to give a shoutout to those of you who helped me figure it out.
/u/Niicodemus - for putting it in layman's terms for me and for the bit about ngrok. At the time I did not have my website hosted so I wouldn't have been able to test it locally without the ngrok tip. It was super easy to set up if anyone has questions.
/u/spookylukey - for diving into Trello docs a bit and helping me understand the HEAD request
and /u/vitorfs's article showed me the general layout and walked me through verifying the IP addresses from trello.
So thank you to everyone who commented, I learned a lot from your help and I'm much more comfortable doing this kind of thing again in the future. For those of you curious (and to help those who have similar questions in the future) here is my code. This is all it takes to get it set up. *Comments and feedback welcome*
**Pip Requirements**
requests
ipaddress
**urls.py**
from django.conf.urls import include, url
from django.contrib import admin
from trello.views import list_webhook
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^trelloCallbacks/', list_webhook, name='trello_webhook'),
]
**trello/views.py**
from django.http import HttpResponse, HttpResponseForbidden
from django.views.decorators.csrf import csrf_exempt
from ipaddress import ip_address, ip_network
import json
from .utils import add_label_to_card
list_before = '<a_trello_list_id>'
list_after = '<another_trello_list_id>'
def check_request_from_trello(forwarded_for):
client_ip_address = ip_address(forwarded_for)
print(client_ip_address)
whitelist = [
"107.23.104.115",
"107.23.149.70",
"54.152.166.250",
"54.164.77.56",
]
for valid_ip in whitelist:
if client_ip_address in ip_network(valid_ip):
print("Request from Trello IP")
break
else:
print("Request from Unknown IP")
return False
return True
@csrf_exempt
def list_webhook(request):
if request.method == "HEAD":
return HttpResponse("OK")
forwarded_for = u'{}'.format(request.META.get('HTTP_X_FORWARDED_FOR'))
if not check_request_from_trello(forwarded_for):
return HttpResponseForbidden("Access Denied, not from Trello")
obj = request.body.decode("utf-8")
data = json.loads(obj)
action = data["action"]
if not action["type"] == "updateCard":
print("Different Action Type")
return HttpResponse(status=200)
if "idList" not in action["data"]["old"]:
print("Card Didn't Move")
return HttpResponse(status=200)
card_id = action["data"]["card"]["id"]
if add_label_to_card(card_id):
print("Added Label")
return HttpResponse(status=200)
**utils.py**
import requests
def add_label_to_card(card_id):
endpoint = "https://api.trello.com/1/cards/"
endpoint += card_id
endpoint += '/labels'
params = {
"name": "logged",
"key": APP_KEY,
"token": TOKEN,
"color": "green"
}
r = requests.post(endpoint, params=params)
if r.status_code == 200:
return True
return r
/r/django
https://redd.it/5jtg26
Hi guys,
A few weeks ago I asked a question about creating a callback url for a webhook [(Original Post Here)](https://www.reddit.com/r/django/comments/5ftsy6/how_do_i_create_a_callback_url_to_consume_a/) and I wanted to give a shoutout to those of you who helped me figure it out.
/u/Niicodemus - for putting it in layman's terms for me and for the bit about ngrok. At the time I did not have my website hosted so I wouldn't have been able to test it locally without the ngrok tip. It was super easy to set up if anyone has questions.
/u/spookylukey - for diving into Trello docs a bit and helping me understand the HEAD request
and /u/vitorfs's article showed me the general layout and walked me through verifying the IP addresses from trello.
So thank you to everyone who commented, I learned a lot from your help and I'm much more comfortable doing this kind of thing again in the future. For those of you curious (and to help those who have similar questions in the future) here is my code. This is all it takes to get it set up. *Comments and feedback welcome*
**Pip Requirements**
requests
ipaddress
**urls.py**
from django.conf.urls import include, url
from django.contrib import admin
from trello.views import list_webhook
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^trelloCallbacks/', list_webhook, name='trello_webhook'),
]
**trello/views.py**
from django.http import HttpResponse, HttpResponseForbidden
from django.views.decorators.csrf import csrf_exempt
from ipaddress import ip_address, ip_network
import json
from .utils import add_label_to_card
list_before = '<a_trello_list_id>'
list_after = '<another_trello_list_id>'
def check_request_from_trello(forwarded_for):
client_ip_address = ip_address(forwarded_for)
print(client_ip_address)
whitelist = [
"107.23.104.115",
"107.23.149.70",
"54.152.166.250",
"54.164.77.56",
]
for valid_ip in whitelist:
if client_ip_address in ip_network(valid_ip):
print("Request from Trello IP")
break
else:
print("Request from Unknown IP")
return False
return True
@csrf_exempt
def list_webhook(request):
if request.method == "HEAD":
return HttpResponse("OK")
forwarded_for = u'{}'.format(request.META.get('HTTP_X_FORWARDED_FOR'))
if not check_request_from_trello(forwarded_for):
return HttpResponseForbidden("Access Denied, not from Trello")
obj = request.body.decode("utf-8")
data = json.loads(obj)
action = data["action"]
if not action["type"] == "updateCard":
print("Different Action Type")
return HttpResponse(status=200)
if "idList" not in action["data"]["old"]:
print("Card Didn't Move")
return HttpResponse(status=200)
card_id = action["data"]["card"]["id"]
if add_label_to_card(card_id):
print("Added Label")
return HttpResponse(status=200)
**utils.py**
import requests
def add_label_to_card(card_id):
endpoint = "https://api.trello.com/1/cards/"
endpoint += card_id
endpoint += '/labels'
params = {
"name": "logged",
"key": APP_KEY,
"token": TOKEN,
"color": "green"
}
r = requests.post(endpoint, params=params)
if r.status_code == 200:
return True
return r
/r/django
https://redd.it/5jtg26
reddit
How do I create a Callback URL to consume a Webhook... • /r/django
Hey guys, I'm an intermediate Python developer (and by that I mean definitely not a beginner, but I still need hand holding at times) and I'm...
very basic python question
can some one please give me the most basic explanation for the following:
Variables
Strings
White Space
Also, Im learning off the book "python crash course" by eric matthes, (great book so far) any way trying to use concatenation to compose a message and the store that message in a variable the book says my line of code should look like the following:
message = "Hello, " + full_name.title() + "!"
print(message)
I keep getting invalid syntax for the "!"
I know this is so very basic, and i was going to skip right over it, till i ran into the problem again but i felt like i might as well, figure out what im doing wrong before moving on. Thanks for the help
#noob
/r/Python
https://redd.it/5jxdkj
can some one please give me the most basic explanation for the following:
Variables
Strings
White Space
Also, Im learning off the book "python crash course" by eric matthes, (great book so far) any way trying to use concatenation to compose a message and the store that message in a variable the book says my line of code should look like the following:
message = "Hello, " + full_name.title() + "!"
print(message)
I keep getting invalid syntax for the "!"
I know this is so very basic, and i was going to skip right over it, till i ran into the problem again but i felt like i might as well, figure out what im doing wrong before moving on. Thanks for the help
#noob
/r/Python
https://redd.it/5jxdkj
reddit
very basic python question • /r/Python
can some one please give me the most basic explanation for the following: Variables Strings White Space Also, Im learning off the book "python...
favicon not showing
Hello I have in the head of my base template.
<link rel="icon" href="{% static "images/favicon.ico" %}" />
This is where my favicon.ico is located it's 16x16, I can access the image in my browser by going to http://127.0.0.1:8000/static/images/favicon.ico.
I've also tried
<link rel="icon" href="/static/images/favicon.ico" />
and just putting favicon in the root directory still nothing.
Also, It seems only to attempt loading the favicon the first time I start the test server every day, I only see the GET favicon.ico 404 my first run. I have the cache disabled so I thought this might force it to look again but I don't think it is. Thank you.
/r/djangolearning
https://redd.it/5jrvly
Hello I have in the head of my base template.
<link rel="icon" href="{% static "images/favicon.ico" %}" />
This is where my favicon.ico is located it's 16x16, I can access the image in my browser by going to http://127.0.0.1:8000/static/images/favicon.ico.
I've also tried
<link rel="icon" href="/static/images/favicon.ico" />
and just putting favicon in the root directory still nothing.
Also, It seems only to attempt loading the favicon the first time I start the test server every day, I only see the GET favicon.ico 404 my first run. I have the cache disabled so I thought this might force it to look again but I don't think it is. Thank you.
/r/djangolearning
https://redd.it/5jrvly
reddit
favicon not showing • /r/djangolearning
Hello I have in the head of my base template. This is where my favicon.ico is...
Logic gates in python
Can logic gates be used in python language and if yes then how does it work? Like examples.
/r/Python
https://redd.it/5jxp8e
Can logic gates be used in python language and if yes then how does it work? Like examples.
/r/Python
https://redd.it/5jxp8e
reddit
Logic gates in python • /r/Python
Can logic gates be used in python language and if yes then how does it work? Like examples.
How to troubleshoot local host connection
Hey all,
I have a little flask project where I am trying to have a login page. The problem I am running into right now is that the local server starts, shows the login page (http://127.0.0.1:5000/) but the page never loads. Does anyone have any suggestions on where to begin to troubleshoot this? I'm not even running any html templates. Aside from cutting out chunks of code I'm sort of stumped.
/r/flask
https://redd.it/5jx41i
Hey all,
I have a little flask project where I am trying to have a login page. The problem I am running into right now is that the local server starts, shows the login page (http://127.0.0.1:5000/) but the page never loads. Does anyone have any suggestions on where to begin to troubleshoot this? I'm not even running any html templates. Aside from cutting out chunks of code I'm sort of stumped.
/r/flask
https://redd.it/5jx41i
reddit
How to troubleshoot local host connection • /r/flask
Hey all, I have a little flask project where I am trying to have a login page. The problem I am running into right now is that the local server...
Question: I'm looking for a rating/ranking system where I can assign weighted scores to multiple attributes of of items.
If this isn't a good place to ask this please ignore/remove.
I'm looking for a system that I can use to rate or rank (I'm not sure if there's a difference) a small set (10-20) items with a few attributes each based on my own arbitrary value for each attribute.
Example: I'm looking to buy a house, and I have a list of ten or so possible candidates. The attributes I will be using to compare will be: price, lot size, floor size, availability of specific high speed internet provider. The importance of each attribute is not equal, nor is the difference equal.
Special features, lots size: The bigger the lot, the better the score, but I also want the lot to be bigger than 10000sqft, so anything below that should get a penalty.
I think I'm ok enough to write the python myself, but I don't have the math to figure this out.
I would guess that something like this must already exists/be defined, but I don't know enough to ask google the right questions.
/r/pystats
https://redd.it/47z8ev
If this isn't a good place to ask this please ignore/remove.
I'm looking for a system that I can use to rate or rank (I'm not sure if there's a difference) a small set (10-20) items with a few attributes each based on my own arbitrary value for each attribute.
Example: I'm looking to buy a house, and I have a list of ten or so possible candidates. The attributes I will be using to compare will be: price, lot size, floor size, availability of specific high speed internet provider. The importance of each attribute is not equal, nor is the difference equal.
Special features, lots size: The bigger the lot, the better the score, but I also want the lot to be bigger than 10000sqft, so anything below that should get a penalty.
I think I'm ok enough to write the python myself, but I don't have the math to figure this out.
I would guess that something like this must already exists/be defined, but I don't know enough to ask google the right questions.
/r/pystats
https://redd.it/47z8ev
reddit
Question: I'm looking for a rating/ranking system... • /r/pystats
If this isn't a good place to ask this please ignore/remove. I'm looking for a system that I can use to rate or rank (I'm not sure if there's a...
Grouping NBA players according to performance [xpost from /r/NBA]
http://www.danvatterott.com/blog/2016/02/21/grouping-nba-players/
/r/pystats
https://redd.it/46xf7m
http://www.danvatterott.com/blog/2016/02/21/grouping-nba-players/
/r/pystats
https://redd.it/46xf7m
Danvatterott
Grouping NBA Players - Dan Vatterott
In basketball, we typically talk about 5 positions: point guard, shooting guard, small forward, power forward, and center. Based on this, one might …
[AF] app.app_context() in thread throws "Working outside of application context from"
Hello, here is my code (simplified):
def __process(app):
with app.app_context(): # <- exception is right here
# work with app..
# work with db..
def process(app):
thread = threading.Thread(target=__process, args=(app))
thread.daemon = True
thread.start()
file with controller:
from flask import current_app
@page.route("bla")
def foo():
process(current_app)
main file:
def run():
app = Flask(__name__, static_folder=None)
setup_database(app)
register_blueprints(app)
app.run()
I've tried putting `with app.app_context()` everywhere, but it does not help - when i try to call the one in `__processs` function - it throws "RuntimeError: Working outside of application context".
Note, that i intentionally do not have access to `app` from controller, so have to use `current_app`, but it works in all other cases.
What is wrong with threaded function?
ps: i am aware about RQ/Celery and going to use something later, but want to sort this out first.
/r/flask
https://redd.it/5jrrsu
Hello, here is my code (simplified):
def __process(app):
with app.app_context(): # <- exception is right here
# work with app..
# work with db..
def process(app):
thread = threading.Thread(target=__process, args=(app))
thread.daemon = True
thread.start()
file with controller:
from flask import current_app
@page.route("bla")
def foo():
process(current_app)
main file:
def run():
app = Flask(__name__, static_folder=None)
setup_database(app)
register_blueprints(app)
app.run()
I've tried putting `with app.app_context()` everywhere, but it does not help - when i try to call the one in `__processs` function - it throws "RuntimeError: Working outside of application context".
Note, that i intentionally do not have access to `app` from controller, so have to use `current_app`, but it works in all other cases.
What is wrong with threaded function?
ps: i am aware about RQ/Celery and going to use something later, but want to sort this out first.
/r/flask
https://redd.it/5jrrsu
reddit
[AF] app.app_context() in thread throws "Working... • /r/flask
Hello, here is my code (simplified): def __process(app): with app.app_context(): # <- exception is right here # work with app.. # work...
Using Python 3.6 in Jupyter in Ubuntu 16.04
# Warning: Following these instructions will set the default Python3 kernel in Jupyter to Python3.6 instead of Python3.5.
## Additional Warning: You will need to install a new copy of any previously installed library to use it in Python3.6.
Using these instructions you will create a virtual environment that contains a copy of Python3.6 so that your system Python will not be effected.
Modified from source at http://stackoverflow.com/questions/1534210/use-different-python-version-with-virtualenv
I needed to install these packages first
sudo apt install libssl-dev
sudo apt install zlib1g-dev
mkdir ~/src
wget http://www.python.org/ftp/python/3.6.0/Python-3.6.0.tgz
tar -zxvf Python-3.6.0.tgz
cd Python-3.6.0
mkdir ~/.localpython
./configure --prefix=$HOME/.localpython
make
make install
## Making the virtual environment
cd ~/src
wget https://pypi.python.org/packages/d4/0c/9840c08189e030873387a73b90ada981885010dd9aea134d6de30cd24cb8/virtualenv-15.1.0.tar.gz#md5=44e19f4134906fe2d75124427dc9b716
tar -zxvf virtualenv-15.1.0.tar.gz
cd virtualenv-15.1.0/
~/.localpython/bin/python3.6 setup.py install
virtualenv ve -p $HOME/.localpython/bin/python3.6
source ve/bin/activate
## Installing Jupyter
pip3.6 install jupyter
pip3.6 install ipython[all] # This may not be needed
To add Python3.6 to Jupyter, while in the virtual environment run the following commands:
## Warning: this will set the Python3 kernel to Python3.6
python3.6 -m pip install ipykernel
python3.6 -m ipykernel install --user
Use "deactivate" when done.
After this the virtual environment does not need to be active to use Python3.6 in Jupyter
## Final Note:
This worked on my machine, but I've installed Jupyter using pip so if you did not install this way you may have to do additional work. This also means I installed all of my libraries using pip as well.
/r/IPython
https://redd.it/5jzsi2
# Warning: Following these instructions will set the default Python3 kernel in Jupyter to Python3.6 instead of Python3.5.
## Additional Warning: You will need to install a new copy of any previously installed library to use it in Python3.6.
Using these instructions you will create a virtual environment that contains a copy of Python3.6 so that your system Python will not be effected.
Modified from source at http://stackoverflow.com/questions/1534210/use-different-python-version-with-virtualenv
I needed to install these packages first
sudo apt install libssl-dev
sudo apt install zlib1g-dev
mkdir ~/src
wget http://www.python.org/ftp/python/3.6.0/Python-3.6.0.tgz
tar -zxvf Python-3.6.0.tgz
cd Python-3.6.0
mkdir ~/.localpython
./configure --prefix=$HOME/.localpython
make
make install
## Making the virtual environment
cd ~/src
wget https://pypi.python.org/packages/d4/0c/9840c08189e030873387a73b90ada981885010dd9aea134d6de30cd24cb8/virtualenv-15.1.0.tar.gz#md5=44e19f4134906fe2d75124427dc9b716
tar -zxvf virtualenv-15.1.0.tar.gz
cd virtualenv-15.1.0/
~/.localpython/bin/python3.6 setup.py install
virtualenv ve -p $HOME/.localpython/bin/python3.6
source ve/bin/activate
## Installing Jupyter
pip3.6 install jupyter
pip3.6 install ipython[all] # This may not be needed
To add Python3.6 to Jupyter, while in the virtual environment run the following commands:
## Warning: this will set the Python3 kernel to Python3.6
python3.6 -m pip install ipykernel
python3.6 -m ipykernel install --user
Use "deactivate" when done.
After this the virtual environment does not need to be active to use Python3.6 in Jupyter
## Final Note:
This worked on my machine, but I've installed Jupyter using pip so if you did not install this way you may have to do additional work. This also means I installed all of my libraries using pip as well.
/r/IPython
https://redd.it/5jzsi2
Stack Overflow
Use different Python version with virtualenv
How do I create a virtual environment for a specified version of Python?
Simple plot - not sure what's up
I'm not sure why I'm not seeing a parabola for this simple plt -
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
# import pandas as pd
# import sympy
def f(x):
return x**x - 4*x + 7
x = np.linspace(-5, 5, 100)
# y = x**x
y = f(x)
plt.plot(
x,
y,
color="green",
marker="o",
linestyle = "solid"
)
plt.grid()
plt.show()
[Here's what mine looks like](http://i.imgur.com/nNhVwZg.png)
I'm expecting something along these lines - https://www.desmos.com/calculator/lvc9vjs91n
If anyone has any other tips / suggestions I'm all ears as I've only just started messing about with this.
Thanks
/r/pystats
https://redd.it/46qu8z
I'm not sure why I'm not seeing a parabola for this simple plt -
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
# import pandas as pd
# import sympy
def f(x):
return x**x - 4*x + 7
x = np.linspace(-5, 5, 100)
# y = x**x
y = f(x)
plt.plot(
x,
y,
color="green",
marker="o",
linestyle = "solid"
)
plt.grid()
plt.show()
[Here's what mine looks like](http://i.imgur.com/nNhVwZg.png)
I'm expecting something along these lines - https://www.desmos.com/calculator/lvc9vjs91n
If anyone has any other tips / suggestions I'm all ears as I've only just started messing about with this.
Thanks
/r/pystats
https://redd.it/46qu8z
Open Science: Reply to 'Influence of cosmic ray variability on the monsoon rainfall and temperature': a false-positive in the field of solar-terrestrial research
http://nbviewer.jupyter.org/github/benlaken/Comment_BadruddinAslam2014/blob/master/Monsoon_analysis.ipynb
/r/JupyterNotebooks
https://redd.it/48xs61
http://nbviewer.jupyter.org/github/benlaken/Comment_BadruddinAslam2014/blob/master/Monsoon_analysis.ipynb
/r/JupyterNotebooks
https://redd.it/48xs61
nbviewer.jupyter.org
Notebook on nbviewer
Check out this Jupyter notebook!
[ANN] IPython 5.0 is out!
https://mail.scipy.org/pipermail/ipython-dev/2016-July/017175.html
/r/IPython
https://redd.it/4ruhol
https://mail.scipy.org/pipermail/ipython-dev/2016-July/017175.html
/r/IPython
https://redd.it/4ruhol
What’s new in matplotlib — Matplotlib 2.0.0rc2 documentation
http://matplotlib.org/2.0.0rc2/users/whats_new.html
/r/Python
https://redd.it/5k0hfo
http://matplotlib.org/2.0.0rc2/users/whats_new.html
/r/Python
https://redd.it/5k0hfo
tablib is one of the most essential and useful python libraries
I recently used [tablib](http://docs.python-tablib.org/), the tabular datasets library for python and found that it makes lots of repetitive tasks in my usual projects (like exporting some data to `CSV`) a whole lot simpler. If you want to export a pickled list or dictionary to say csv, json or even an xls, all you have to do is this:
with open('filename.csv', 'wb') as f:
f.write(data.csv.encode('UTF-8'))
with open('filename.json', 'wb') as f:
f.write(data.json.encode('UTF-8'))
with open('filename.yaml', 'wb') as f:
f.write(data.yaml.encode('UTF-8'))
with open('filename.xls', 'wb') as f:
f.write(data.xls)
where data is a tablib dataset initialized like this:
data = tablib.Dataset()
and appended like this:
data.headers = ['col-1', 'col-2', 'col-3']
data.append(my_list)
Hope you find this pythonic library useful.
Merry Christmas to you all!
/r/Python
https://redd.it/5jyvzi
I recently used [tablib](http://docs.python-tablib.org/), the tabular datasets library for python and found that it makes lots of repetitive tasks in my usual projects (like exporting some data to `CSV`) a whole lot simpler. If you want to export a pickled list or dictionary to say csv, json or even an xls, all you have to do is this:
with open('filename.csv', 'wb') as f:
f.write(data.csv.encode('UTF-8'))
with open('filename.json', 'wb') as f:
f.write(data.json.encode('UTF-8'))
with open('filename.yaml', 'wb') as f:
f.write(data.yaml.encode('UTF-8'))
with open('filename.xls', 'wb') as f:
f.write(data.xls)
where data is a tablib dataset initialized like this:
data = tablib.Dataset()
and appended like this:
data.headers = ['col-1', 'col-2', 'col-3']
data.append(my_list)
Hope you find this pythonic library useful.
Merry Christmas to you all!
/r/Python
https://redd.it/5jyvzi
[Ask-Flask] Set a column value before commit using Flask-SQLAlchemy.
I'm writing a URL shortener API using Flask, and I'm stuck with something in my model.
I have a `Url` model with the following attributes and method:
class Url(db.Model):
# ...
id = db.Column(db.Integer, primary_key=True)
key = db.Column(db.String, unique=True, index=True)
def generate_key(self):
"""Generates a Base62 key for the URL based on its ID."""
self.key = encode(self.id)
# ...
I have a helper function `encode` that takes an integer, and returns a Base62-encoded string.
I want to pass an instance's `id` to generate the string, which I can then use to set the `key` attribute before the session commit. I searched, and the answers talked about using `db.session.flush()`. This sets the `id` attribute.
If I open a Python shell and do it manually it works fine:
>>> u1 = Url()
>>> db.session.add(u1)
>>> db.session.flush()
>>> u1.id
1
>>> u1.generate_key()
>>> u1.key
'a'
>>> u2 = Url()
>>> db.session.add(u2)
>>> db.session.flush()
>>> u2.id
2
>>> u2.generate_key()
>>> u2.key
'b'
>>> db.session.commit()
I want to automate these steps using some sort of event listener. For example, suppose I'm creating a new `Url` instance in a view. I want the key to be generated automatically either after I manually call `db.session.flush()` or right before a commit as I call `db.session.commit()`.
I saw the following events `after_flush`, `before_commit` and `after_insert` in the docs, but I can't seem to get it to work.
I got different errors including:
> sqlalchemy.exc.ArgumentError: Session event listen on a scoped_session requires that its creation callable is associated with the Session class.
> sqlalchemy.exc.InvalidRequestError: No such event 'after_flush' for target '<class 'app.models.Url'>'
Edit: I realised I could just do that in the view: create a new instance, flush, generate key, and then commit. But I wanted to see if there's another way of doing it. I just thought that logic should belong to the model.
/r/flask
https://redd.it/5dn2vb
I'm writing a URL shortener API using Flask, and I'm stuck with something in my model.
I have a `Url` model with the following attributes and method:
class Url(db.Model):
# ...
id = db.Column(db.Integer, primary_key=True)
key = db.Column(db.String, unique=True, index=True)
def generate_key(self):
"""Generates a Base62 key for the URL based on its ID."""
self.key = encode(self.id)
# ...
I have a helper function `encode` that takes an integer, and returns a Base62-encoded string.
I want to pass an instance's `id` to generate the string, which I can then use to set the `key` attribute before the session commit. I searched, and the answers talked about using `db.session.flush()`. This sets the `id` attribute.
If I open a Python shell and do it manually it works fine:
>>> u1 = Url()
>>> db.session.add(u1)
>>> db.session.flush()
>>> u1.id
1
>>> u1.generate_key()
>>> u1.key
'a'
>>> u2 = Url()
>>> db.session.add(u2)
>>> db.session.flush()
>>> u2.id
2
>>> u2.generate_key()
>>> u2.key
'b'
>>> db.session.commit()
I want to automate these steps using some sort of event listener. For example, suppose I'm creating a new `Url` instance in a view. I want the key to be generated automatically either after I manually call `db.session.flush()` or right before a commit as I call `db.session.commit()`.
I saw the following events `after_flush`, `before_commit` and `after_insert` in the docs, but I can't seem to get it to work.
I got different errors including:
> sqlalchemy.exc.ArgumentError: Session event listen on a scoped_session requires that its creation callable is associated with the Session class.
> sqlalchemy.exc.InvalidRequestError: No such event 'after_flush' for target '<class 'app.models.Url'>'
Edit: I realised I could just do that in the view: create a new instance, flush, generate key, and then commit. But I wanted to see if there's another way of doing it. I just thought that logic should belong to the model.
/r/flask
https://redd.it/5dn2vb
reddit
[Ask-Flask] Set a column value before commit using... • /r/flask
I'm writing a URL shortener API using Flask, and I'm stuck with something in my model. I have a `Url` model with the following attributes and...
How do I change the home directory?
Hi all. I am running on Windows 10. When I open the Jupyter Notebook launcher, my home directory is My Documents. I would like for Jupyter to start one level back. This works if I run iPython from the command prompt, but I would like the luxury of running Jupyter with a shortcut launcher. Is there anyway to configure this? I already checked online (http://jupyter-notebook-beginner-guide.readthedocs.io/en/latest/execute.html), and this was not helpful. If I follow these instructions, my starting path is already C:\Users\MY_NAME. I would like Jupyter to start here instead of C:\Users\MY_NAME\My_Documents.
/r/IPython
https://redd.it/4r37yd
Hi all. I am running on Windows 10. When I open the Jupyter Notebook launcher, my home directory is My Documents. I would like for Jupyter to start one level back. This works if I run iPython from the command prompt, but I would like the luxury of running Jupyter with a shortcut launcher. Is there anyway to configure this? I already checked online (http://jupyter-notebook-beginner-guide.readthedocs.io/en/latest/execute.html), and this was not helpful. If I follow these instructions, my starting path is already C:\Users\MY_NAME. I would like Jupyter to start here instead of C:\Users\MY_NAME\My_Documents.
/r/IPython
https://redd.it/4r37yd
[D] Deep Learning Race: A Survey of Industry Players’ Strategies – Intuition Machine
https://medium.com/intuitionmachine/the-different-ways-that-internet-giants-approach-deep-learning-research-753c9f99d9f1#.axn5kt1ny
/r/MachineLearning
https://redd.it/5jyg0e
https://medium.com/intuitionmachine/the-different-ways-that-internet-giants-approach-deep-learning-research-753c9f99d9f1#.axn5kt1ny
/r/MachineLearning
https://redd.it/5jyg0e
Medium
Deep Learning Race: A Survey of Industry Players’ Strategies
I’ve been working for quite a while now in trying to make sense of the research developments in Deep Learning. The methodology I’ve…
What is wrong?
on terminal, it works good, but on ipython notebook it doesn't work.
```sumoProcess = subprocess.Popen([sumoBinary, "-c", "data/cross.sumocfg", "--tripinfo-output","tripinfo.xml", "--remote-port", str(PORT)], stdout=sys.stdout, stderr=sys.stderr)```
UnsupportedOperationTraceback (most recent call last)
<ipython-input-15-80cdeae4d531> in <module>()
----> 1 sumoProcess = subprocess.Popen([sumoBinary, "-c", "data/cross.sumocfg", "--tripinfo-output","tripinfo.xml", "--remote-port", str(PORT)], stdout=sys.stdout, stderr=sys.stderr)
/usr/lib/python2.7/subprocess.pyc in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags)
700 (p2cread, p2cwrite,
701 c2pread, c2pwrite,
--> 702 errread, errwrite), to_close = self._get_handles(stdin, stdout, stderr)
703
704 try:
/usr/lib/python2.7/subprocess.pyc in _get_handles(self, stdin, stdout, stderr)
1126 else:
1127 # Assuming file-like object
-> 1128 c2pwrite = stdout.fileno()
1129
1130 if stderr is None:
/usr/local/lib/python2.7/dist-packages/ipykernel/iostream.pyc in fileno(self)
304
305 def fileno(self):
--> 306 raise UnsupportedOperation("IOStream has no fileno.")
307
308 def write(self, string):
UnsupportedOperation: IOStream has no fileno.
Python 2.7.6
/r/IPython
https://redd.it/4q13m9
on terminal, it works good, but on ipython notebook it doesn't work.
```sumoProcess = subprocess.Popen([sumoBinary, "-c", "data/cross.sumocfg", "--tripinfo-output","tripinfo.xml", "--remote-port", str(PORT)], stdout=sys.stdout, stderr=sys.stderr)```
UnsupportedOperationTraceback (most recent call last)
<ipython-input-15-80cdeae4d531> in <module>()
----> 1 sumoProcess = subprocess.Popen([sumoBinary, "-c", "data/cross.sumocfg", "--tripinfo-output","tripinfo.xml", "--remote-port", str(PORT)], stdout=sys.stdout, stderr=sys.stderr)
/usr/lib/python2.7/subprocess.pyc in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags)
700 (p2cread, p2cwrite,
701 c2pread, c2pwrite,
--> 702 errread, errwrite), to_close = self._get_handles(stdin, stdout, stderr)
703
704 try:
/usr/lib/python2.7/subprocess.pyc in _get_handles(self, stdin, stdout, stderr)
1126 else:
1127 # Assuming file-like object
-> 1128 c2pwrite = stdout.fileno()
1129
1130 if stderr is None:
/usr/local/lib/python2.7/dist-packages/ipykernel/iostream.pyc in fileno(self)
304
305 def fileno(self):
--> 306 raise UnsupportedOperation("IOStream has no fileno.")
307
308 def write(self, string):
UnsupportedOperation: IOStream has no fileno.
Python 2.7.6
/r/IPython
https://redd.it/4q13m9
reddit
What is wrong? • /r/IPython
on terminal, it works good, but on ipython notebook it doesn't work. ```sumoProcess = subprocess.Popen([sumoBinary, "-c", "data/cross.sumocfg",...
[AF]cannot get environment variables set in Flask application
Hi,
I tried to set up sensitive information as environment variables in CentOS, and pass them to Flask config file used in main file, i.e. __init__.py . But it did not work. The Flask application is running under Apache.
I first edit /etc/environment as root user
MAIL_USERNAME="abcde@abc.com"
then logout, login again
Then verify MAIL_USERNAME is set by running
echo $MAIL_USERNAME
This works fine
And in configuration.py, this is how I set MAIL_USERNAME.
MAIL_USERNAME = os.environ.get('MAIL_USERNAME')
for testing purpose,
I print out MAIL_USERNAME
in __init__.py
print(MAIL_USERNAME)
Then from terminal, if I run
python3.4 __init__.py
it print out correct values of MAIL_USERNAME
However, if I tested on web browser, MAIL_USERNAME is just not set. it shows NONE. I verify this by looking Apache log.
Any idea of how this works would be really appreciated.
Thanks
/r/flask
https://redd.it/5dc4dn
Hi,
I tried to set up sensitive information as environment variables in CentOS, and pass them to Flask config file used in main file, i.e. __init__.py . But it did not work. The Flask application is running under Apache.
I first edit /etc/environment as root user
MAIL_USERNAME="abcde@abc.com"
then logout, login again
Then verify MAIL_USERNAME is set by running
echo $MAIL_USERNAME
This works fine
And in configuration.py, this is how I set MAIL_USERNAME.
MAIL_USERNAME = os.environ.get('MAIL_USERNAME')
for testing purpose,
I print out MAIL_USERNAME
in __init__.py
print(MAIL_USERNAME)
Then from terminal, if I run
python3.4 __init__.py
it print out correct values of MAIL_USERNAME
However, if I tested on web browser, MAIL_USERNAME is just not set. it shows NONE. I verify this by looking Apache log.
Any idea of how this works would be really appreciated.
Thanks
/r/flask
https://redd.it/5dc4dn
reddit
[AF]cannot get environment variables set in Flask... • /r/flask
Hi, I tried to set up sensitive information as environment variables in CentOS, and pass them to Flask config file used in main file, i.e. ...