Archive
Flask: linkify a text
Problem
I have a text that I present in a Flask application. The text can contain URLs, and I would like to linkify them, i.e. make them clickable links. Example:
before:
visit http://google.com for...
after:
visit <a href="http://google.com">http://google.com</a> for...
Solution
Before rolling out an own solution, it’s a good idea to check if there is a package for this problem. There is :), and it’s called bleach. Its usage couldn’t be simpler:
>>> import bleach
>>> bleach.linkify('an http://example.com url')
u'an <a href="http://example.com" rel="nofollow">http://example.com</a> url
Flask integration
In your main file (that calls app.run()) add the following filter:
import bleach
@app.template_filter('linkify')
def linkify(s):
return bleach.linkify(s)
Then use it in your jinja2 templates:
Description: {{ entry.description|linkify|safe }}
Warning! Apply the “safe” filter only if you trust the origin of the text you want to present in a linkified format.
subtract a day from a python date
Problem
When working with dates, I prefer the order yyyy-mm-dd (e.g. 2015-07-10). Its main advantage is that if you use it as a prefix and sort your entries, you get them in chronological order. (Another advantage is that in my home country we use this order, so this is much closer to my thinking).
So, I faced the following problem: having a date as a string (“2015-07-10”), calculate the date one day before and produce a string again (“2015-07-09”).
Solution
>>> from datetime import datetime, timedelta
>>> date = "2015-07-10"
>>> today = datetime.strptime(date, '%Y-%m-%d')
>>> today
datetime.datetime(2015, 7, 10, 0, 0)
>>> yesterday = today - timedelta(days=1)
>>> yesterday
datetime.datetime(2015, 7, 9, 0, 0)
>>> yesterday.strftime('%Y-%m-%d')
'2015-07-09'
Links
- http://stackoverflow.com/questions/466345/converting-string-into-datetime
- http://stackoverflow.com/questions/441147/how-can-i-subtract-a-day-from-a-python-date
Remark
Back to dates: if I need to write a date in English, I write it like this: “May 12, 1984”. Avoid “05-12-1984”, because what is it? May 12? Or December 5? God knows only.
Python course in Milan, Italy
In the last two days I gave an intensive Python course at the University of Milan, Italy. It was good. As I saw the students liked it too :)
Here is the schedule of the course:
Day 1 ===== - introduction - string data type - list data type - loops (for, while) - tuple data type - list comprehension - control structures - functions Day 2 ===== - set - dictionary - global variables - file handling - classes, objects - modules - random numbers - downloading webpages - JSON serialization
touch a file
Problem
In bash, the command “touch” creates an empty file (with size 0). How to do this in Python?
Solution
Simply open a file in write mode and write an empty string to it.
With the stdlib:
with open("empty.txt", "w") as f:
f.write("")
With the excellent unipath library:
p = Path("empty.txt")
p.write_file("")
Note that this solution will overwrite your file if it exists. So be careful.
Simplicity is the final achievement.
“Simplicity is the final achievement. After one has played a vast quantity of notes and more notes, it is simplicity that emerges as the crowning reward of art.”
Frederic Chopin
how to become a data scientist in Python
In this post I found a detailed learning path on how to become proficient in data science.
They also made an infographic (see this post).
Click to see the full version.
(Here is a backup of the image if the original site went down.)
creating a Python 3 virt. env. on Ubuntu
Problem
Python 3 on Ubuntu is sometimes a total mess. I wanted to create a Python 3 virt. env., but I got this error:
$ virtualenv -p python3 venv
Running virtualenv with interpreter /usr/bin/python3
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 8, in
import base64
File "/usr/lib/python3.4/base64.py", line 9, in
import re
File "/usr/lib/python3.4/re.py", line 324, in
import copyreg
File "/usr/local/lib/python2.7/dist-packages/copyreg.py", line 3, in
from copy_reg import *
ImportError: No module named 'copy_reg'
Error in sys.excepthook:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 53, in apport_excepthook
if not enabled():
File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 24, in enabled
import re
File "/usr/lib/python3.4/re.py", line 324, in
import copyreg
File "/usr/local/lib/python2.7/dist-packages/copyreg.py", line 3, in
from copy_reg import *
ImportError: No module named 'copy_reg'
Original exception was:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/virtualenv.py", line 8, in
import base64
File "/usr/lib/python3.4/base64.py", line 9, in
import re
File "/usr/lib/python3.4/re.py", line 324, in
import copyreg
File "/usr/local/lib/python2.7/dist-packages/copyreg.py", line 3, in
from copy_reg import *
ImportError: No module named 'copy_reg'
Awesome! :(
Solution
I found a working solution here. The following command let me create a Python 3 virt. env.:
python3 -c 'import sys; del sys.argv[0]; s = sys.argv[0]; exec(open(s).read(), {"__file__": s, "__name__": "__main__"})' `which virtualenv` -p python3 venv
Life on Arch / Manjaro is easier. There Python 3 has been the default for years.
PyCon US 2015 videos
PyCon US 2015 took place in Montréal, Canada (just like last year). The videos are being uploaded to pyvideo.org. I think we need some more weeks till all the videos get uploaded but at the moment of writing this post there are already 134 videos available.
Here is a nice script of mine (pyvideo_popularity.py) that orders presentations by popularity.
Talk Python To Me: a Python podcast
I just found this Python podcast: http://www.talkpythontome.com/. In the latest episode you can find an interview with “Jesse Davis from MongoDB. Jesse is the maintainer for a number of popular open-source projects including the Python MongoDB driver known as PyMongo and Mongo C (for C/C++ developers, yes you read right! C developers). Jesse discusses how interesting it is to write both Python and C code and how it reawakens part of the brain.” (source)



You must be logged in to post a comment.