PythoFF

Menu

Sign in:

read us on

Основные концепции журналирования в Python

По мере того, как усложняется структура приложения, ведение логов (журналирование) становится всё полезнее для разработчика. Логи не только пригодятся в процессе отладки, но и помогут обнаружить скрытые проблемы проекта, а также отследить его производительность.

home/2019/04/16/b841af8c938beee1af14181040509d9d93665ef3.jpg

Hands-on Python 3 Concurrency With the asyncio Module

Learn how to speed up your Python 3 programs using concurrency and the asyncio module in the standard library. See step-by-step how to leverage concurrency and parallelism in your own programs, all the way to building a complete HTTP downloader example app using asyncio and aiohttp.

Пишем одностраничное приложение с Flask и Vue.js

Эта статья — пошаговое руководство по настройке базового CRUD-приложения с помощью Vue и Flask. Начнём с создания нового приложения Vue, используя Vue CLI, а затем перейдём к выполнению основных операций CRUD с помощью RESTful API на бэкенде под управлением Python и Flask.

home/2019/04/15/762e665f1413e6f8b00ff449b23ec53ae5f3339d.jpg

Linear Regression in Python

In this step-by-step tutorial, you'll get started with linear regression in Python. Linear regression is one of the fundamental statistical and machine learning techniques, and Python is a popular choice for machine learning.

PyDev of the Week: Pierre Denis

This week we welcome Pierre Denis as our PyDev of the Week! Pierre is the creator of Lea, a probabilistic programming package in Python. He can be found on LinkedIn where you can see his CV and learn more about some of the things he is up to. Let’s take a few moments to get to know Pierre better! Can you tell us a little about yourself (hobbies, education, etc): I’ve a Master in Computer Science from UCL Louvain-la-Neuve, Belgium, where I reside. I’m working since 20 years as software engineer in [Spacebel](http://www.spacebel.be), a company developing systems for Space. Basically, I like everything creative and elegant. Beside arts, music, literature, I ‘m looking for this in physics, algorithmic, GUI and mathematics. I love programming, especially in Python. So far, I have initiated three open-source Python projects: UFOPAX (textual virtual universe), Unum (quantities with unit consistency) and Lea (probabilistic programming). For these developments, I tend to be perfectionist and consequently slow: I’m the kind of guy that re-write the same program ten times, just for the sake of inner beauty! Beside programming, I’m doing research in number theory (twin primes conjecture). Also, I’m writing short stories in French, my mother tongue, with some reference to the ‘Pataphysics of Alfred Jarry and a lot of nonsense. Incidentally and fortunately, programs can be good for producing nonsense, as I showed in my bullshit generator! Continue reading PyDev of the Week: Pierre Denis →

home/2019/04/14/6d917c4499fd3512c7a4c1286dfa62cde2005fe5.jpg

Python String Formatting Tips & Best Practices

Learn the four main approaches to string formatting in Python, as well as their strengths and weaknesses. You'll also get a simple rule of thumb for how to pick the best general purpose string formatting approach in your own programs.

Python Used to Take Photo of Black Hole

Scientists have used a new algorithm to take a photo of a black hole. One of the most exciting parts about it to me is that they used a lot of Python libraries to do the magic. Here’s a list mentioned in their paper: Numpy (van der Walt et al. 2011) Scipy (Jones et al. 2001) Pandas (McKinney 2010) Jupyter (Kluyver et al. 2016) Matplotlib (Hunter 2007). Astropy (The Astropy Collaboration et al. 2013, 2018) They also used their own custom Python code which is available on Github If you’re interested in a more laymen’s explanation of the ideas behind taking the photo, there’s a nice TED talk on it from one of the researchers: Related Links Reddit Python group discussing these developments A Photo of the researcher that appears to show Matplotlib running.

home/2019/04/09/a1f949e84cb8a3fc620f80f3dc408657a2dd39c0.jpg

Running Python Scripts

This step-by-step course will guide you through a series of ways to run Python scripts, depending on your environment, platform, needs, and skills as a programmer.

ReportLab: Adding a Chart to a PDF with Python

The ReportLab toolkit supports adding many different charts and graphs to your PDFs. In fact, I have covered some of them in a previous article. However most of the examples I have seen, including the ones in my own article, do not show how to insert a chart as a Flowable. What that means is that most examples show you how to create a PDF with a single page that contains the chart in it. Most developers would want to be able to create some text, perhaps a table and insert the chart along with those elements. You would also usually have additional text following the chart. For this article, you will learn how to do just that. Continue reading ReportLab: Adding a Chart to a PDF with Python →

home/2019/04/08/37b50864a3c49d87b1786bad7821a3bb9eb11626.jpg

Python REST APIs With Flask, Connexion, and SQLAlchemy – Part 3

In Part 3 of this series, you'll learn how to add relationships to the database created in Part 2 and extend the API to support CRUD operations on those relationships using SQLAlchemy and Marshmallow.

PyDev of the Week: Abdur-Rahmaan Janhangeer

This week we welcome Abdur-Rahmaan Janhangeer as our PyDev of the Week! Abdur-Rahmaan is the French translator of Think Python. You can see what he is up to on his blog as well as on Github. Let’s take a few moments to get to know him better! Can you tell us a little about yourself (hobbies, education, etc): I’m Abdur-Rahmaan Janhangeer from Mauritius, a paradise island in the Indian Ocean and currently one of the best tourist destinations. I have an IT business and i am shyly becoming a Python Trainer. I am mostly self-taught in programming. Concerning Python, I’m the Arabic Coordinator for the Python docs, translator of Think Python into French (publishing soon) and organising member for the py user-group of Mauritius. I also did some really tiny contributions to LinuxMint, Numpy and Odoo. As “hobby”, i like to dig into Compiler Theory and code some toy langs in my spare time. Being a gallery moderator, I use InkScape to design logos and business cards for people. Playing around with graphics! Continue reading PyDev of the Week: Abdur-Rahmaan Janhangeer →

home/2019/04/04/89fe5039a52a329d89f8abd6c4d1f9af75b55c9f.jpg

Python Development in Visual Studio Code (Setup Guide)

In this course, you'll learn how to use Visual Studio Code for Python development. By following examples, you'll cover everything from how to install and configure Visual Studio Code for Python development to how to run tests and debug application, so you can use this powerful tool.

home/2019/04/03/07adb53fc0c78a7843cf0acca01ac1c503845e78.jpg

What Is Pip? A Guide for New Pythonistas

What is pip? In this beginner-friendly tutorial, you'll learn how to use pip, the standard package manager for Python, so that you can install and manage additional packages that are not part of the Python standard library.

home/2019/04/02/8a71065e3ad9e6c48b1fd8c7d38410430cd83d14.jpg

Idiomatic Pandas: Tricks & Features You May Not Know

In this course you'll see how to use some lesser-used but idiomatic Pandas capabilities that lend your code better readability, versatility, and speed.

Product Review: Python Flash Cards

No Starch Press is best known for creating books on computer programming. However they recently released a new product called Python Flash Cards by Eric Matthes, the author of Python Crash Course. I thought this was a unique product and decided to ask for a review copy. The cards and their box are high quality. I like the card stock they used quite a bit. The cards themselves target Python 3.7. Each card is marked with a color along their top that matches their category: The cards are also numbered. This is useful for the times where the cards make reference to other cards in their section or other sections entirely. It makes referring to different cards nice and straight-forward. Of course, flash cards are by their very nature, short and to the point. So the testing and packaging sections of cards feel too brief to me. On the other hand, they are flash cards, so the medium doesn’t allow them to be fleshed out the way I would want them to be. If you need more details, Google is never far away. While I am certainly not the target market for these cards, I think they will work well for high school students and possibly even freshmen in college that want to learn. They are certainly useful for refreshing yourself on the basics of Python. If you have students, this set may prove quite useful for them. Python Flash Cards by Eric Matthes Amazon, No Starch Book Reviews Book Review – Mission Python: Code a Space Adventure Game! by Sean McManus Serious Python: Black-Belt Advice on Deployment, Scalability, Testing, and More by Julien Danjou Python Testing with pytest by Brian Okken Module Programming with Python by Erik Westra Python Playground – Geeky Projects for the Curious Programmer by Mahesh Venkitachalam IPython Notebook Essentials by L. Felipe Martins

home/2019/04/01/7dd3e2a57262c040192633d8a5975821f8865152.jpg

Get Started With Django Part 1: Build a Portfolio App

In this step-by-step tutorial, you'll learn the basics of creating powerful web applications with Django, a Python web framework. You'll build a portfolio application to showcase your web development projects, complete with a fully functioning blog.

My Cover Story for Creating GUI Applications with wxPython Book

I thought it would be fun to write a bit about the cover art for my new book, Creating GUI Applications with wxPython. I had meant to post about that during the actual Kickstarter campaign. My original idea for the cover was to have the mouse directing a Phoenix to attack a snake. The Phoenix is a reference to the code name for wxPython 4 before it was released and you can still see references to Phoenix in the documentation and the artwork on some of the pages for the wxPython project. In fact, I commissioned that cover to be done. Here’s a sketch of it: Original cover concept art As you can see, the artist had trouble remembering that the snake should be a Python. He continued to make lazy mistakes in the finished product and I ended up scrapping that cover. I am not sure if I will use that cover for a future book or not. I personally like the look of the mouse and Phoenix, but the Python will always bother me. So I ended up hiring Varya Kolesnikova again for the actual cover of the book. She is the artist who did my Python 201 cover art. You can view more of her art on Behance or Instagram. Here is her original sketch of my new concept, which was to have the mouse riding the Phoenix and carrying the Python: Actual cover concept art sketch I liked her approach much better, although her idea of a Phoenix was very different than my original vision for it. Here is a color version of the concept art: Color concept art sketch I liked Varya’s approach to the art and she ended up finishing the artwork as you know today: Final cover art I am hard at work wrapping up the last few chapters of the book. If you are interested in getting early access to the book, you can pre-order it now on Leanpub. The final version of the book will be released in May 2019.

PyDev of the Week: Kyle Stratis

This week we welcome Kyle Stratis (@KyleStratis) as our PyDev of the Week! He is an active contributor at Real Python but also maintains his own website. You can catch up with his projects on Github as well. Let’s take a few moments to get to know Kyle! Can you tell us a little about yourself (hobbies, education, etc): I’m a self-taught developer, I actually studied neuroscience up through graduate school, with a focus on mechanisms of attention in the auditory system. The coding I had to do at every step of the experimental process rekindled my early love of the craft, and a good friend stepped in as a mentor – so I taught myself and got my first job while I was writing my master’s thesis. While I do a lot of programming on the side, I also enjoy weightlifting (my father was a bodybuilder and gym-owner, with 4x Mr. Olympia Jay Cutler starting at his gym, so maybe it’s genetic), skateboarding, and surfing, which I do noticeably less of now that I live in Boston. I’m also a bit of a metalhead, so on any given weekend you’ll be likely to find me at a dingy club with a battlevest on and cheap beer in hand. I’d be remiss to not mention spending time with my wife, which usually is spent reading, hiking, and playing with our 2 cats. Continue reading PyDev of the Week: Kyle Stratis →

Реверс-инжиниринг для начинающих: продвинутые концепции программирования

В первой части мы рассмотрели базовые концепции программирования, такие как циклы и условный оператор, в этой статье будем рассматривать более сложные темы, необходимые для реверс-инжиниринга.

wxPython 4 and PubSub

The Publish-Subscribe pattern is pretty common in computer science and very useful too. The wxPython GUI toolkit has had an implementation of it for a very long time in wx.lib.pubsub. This implementation is based on the PyPubSub package. While you could always download PyPubSub and use it directly instead, it was nice to be able to just run wxPython without an additional dependency. However, as of wxPython 4.0.3, wx.lib.pubsub is now deprecated and will be removed in a future version of wxPython. So now you will need to download PyPubSub or PyDispatcher if you want to use the Publish-Subscribe pattern easily in wxPython. Installing PyPubSub You can install PyPubSub using pip. Here’s how to do it: pip install pypubsub PyPubSub should install quite quickly. Once it’s done, let’s find out how to use it! Continue reading wxPython 4 and PubSub →

home/2019/03/28/42126151b9179f3c9df642e52d51737ce4edc2c0.jpg

How to Stand Out in a Python Coding Interview

In this step-by-step tutorial, you'll learn how to take your Python coding interview skills to the next level and use Python's built-in functions and modules to solve problems faster and more easily.

Book Review: Mission Python

A couple of months ago, No Starch Press asked me if I would be interested in reading one of their new books called Mission Python: Code a Space Adventure Game! by Sean McManus. I enjoy reading new tech books, but it’s hard to work them in when I’ve been so busy this past year. However one of my resolutions for 2019 is to read through my backlog of tech books, so I decided to tackle this one next! Quick Review Why I picked it up: Originally, the publisher asked me check the book out, but I was also interested because I think game programming is intriguing Why I finished it: I mostly skimmed this book, but it’s definitely worth a read to see how to put a game together I’d give it to: Developers that want to learn how quickly and easily it is to write a 2D game in Python Continue reading Book Review: Mission Python →

PyDev of the Week: Miro Hrončok

This week we welcome Miro Hrončok (@hroncok) as our PyDev of the Week! Miro teaches at Czech Technical University and helps out with the local PyLadies chapter. He is also involved with the Special Interest Group for Python in Fedora as he works for Red Hat in addition to his teaching position. You can check out some of the projects he is involved in over on Github or check out his website. Let’s take a few moments to get to know Miro better! Can you tell us a little about yourself (hobbies, education, etc): I’m a guy from Prague, Czech Republic, in my late twenties, yet both of my parents are from Košice, Slovakia, so I’m kinda both Czech and Slovak. I’ve studied Pascal at a gymnasium and later did my bachelors and masters in Computer Science/Software Engineering at the Faculty of Information Technology, Czech Tecnical University in Prague. Most of my hobbies are related to computers and technology but apart from that I have two Irish Wolfhounds and I love to ski. One of my dogs when she was little My technological interest has always been connected to Free and Open Source Software (and Hardware), starting with the Czech Linux community when I was a teenager, co-founding the RepRap 3D Printing Lab during my early years at the university and joining Fedora and later Red Hat, now working in the Python Maintenance team, also pro-active in the Czech Python community. Continue reading PyDev of the Week: Miro Hrončok →

home/2019/03/28/52d43b493e4b980d2548d4b023783026312396c7.jpg

Python for Programmers eBook Giveaway

UPDATE: All copies of the book have now been claimed! Thanks for checking it out! Pearson recently contacted me about doing a giveaway of their new Python book, Python for Programmers: with Big Data and Artificial Intelligence Case Studies I have 5 copies of the eBook to giveaway. All you need to do to claim a copy is tweet this article and tag me @driscollis and then send me a direct message on Twitter with the link or send the link to me via the Contact form on this blog. Here’s some more information about the book from their website: Written for developers with a background in any high-level language, Introduction to Python and Data Science for Programmers explores the Python language and Python APIs in depth, applying the Deitels’ signature live-code approach to teaching programming. Paul Deitel and Dr. Harvey M. Deitel present concepts in the context of fully tested programs, complete with syntax shading, code highlighting, line-by-line code walkthroughs, and program outputs. They feature hundreds of complete Python programs with nearly 20,000 lines of proven Python code, and hundreds of tips to help you build robust applications. You’ll start with an introduction to Python using an early classes and objects approach, and then rapidly move on to more advanced topics. Throughout, you’ll enjoy the Deitels’ classic treatment of object-oriented programming. By the time you’re finished, you’ll have everything you need to build industrial-strength Python applications.

Декораторы в Python: понять и полюбить

Декораторы — один из самых полезных инструментов в Python, однако новичкам они могут показаться непонятными. Возможно, вы уже встречались с ними, например, при работе с Flask, но не хотели особо вникать в суть их работы. Эта статья поможет вам понять, чем являются декораторы и как они работают.

Искусство парсинга или DOM своими руками

Привет, Хабр! Недавно я задался идеей создать простой язык разметки наподобие markdown, который отлично подходил бы для моих задач, а именно — быстрого написания лекций с форматированием и возможностью вставки математических формул «на лету», с применением одной лишь клавиатуры. Чтобы перевести текст, написанный в таком формате, в более понятную форму, например, документ LibreOffice Writer, нужен синтаксический анализатор, проще говоря — парсер. Поскольку я привык делать велосипеды, то направился в поисковые системы с запросами «parser example», «html to DOM», «how to parse html» и др. К моему разочарованию, на всех найденных ресурсах либо приводились элементарные примеры типа калькулятора Страуструпа с рекурсивным спуском, либо использовались готовые решения, такие как flex, bison, llvm и yacc. Библиотек, предназначенных для парсинга строго определённых языков, нашлось ещё больше (gumbo, jsoup, rapidjson, инструменты Qt и др.) Ни то, ни другое не входило в мои планы по написанию парсера своей разметки на C++ с использованием лишь стандартной библиотеки, поэтому моим источником знаний об искусстве парсинга вместо электронных ресурсов стали методички технических институтов. О том, как взять текст и построить из него AST (абстрактное синтаксическое дерево), о некоторых подводных камнях, на которые я натыкался в процессе, о возможных ошибках я сегодня и расскажу. Сразу оговорюсь, — если ваша цель — свой скриптовый язык или что ещё сложнее, этой статьи будет недостаточно для его реализации. В идеале нужно на отлично знать теорию автоматов и дискретные структуры. Но в качестве отправной точки можно пока ограничиться и моим опытом, которым я щедро поделюсь под катом. Это не совсем то, что я задумывал изначально, зато идеально подходит для примера. Парсить мы будем HTML, как простой и всем знакомый язык.

home/2019/03/07/079f6f636429dc0779cc7b6aa67dbbe2db41a938.jpg

Виртуальный Джинн на 8 марта — или как удивить своих сотрудниц в самый весенний день

Завтра по всему миру мы будем отмечать самый женский день в году. И это прекрасно! Но это значит, что сегодня — день, когда мы поздравляем наших дорогих сотрудниц. И каждый год мы (мужская часть трудового коллектива) думаем, как бы сделать это по-особенному… Цветы, вечерний банкет — все эти милые банальности приятны, но в 21-м веке всем хочется чего-то технологичненького и современненького. Вот мы в Just AI думали-думали и таки придумали! Под катом — уже готовый туториал, который вы тоже можете запустить прямо сейчас и превратить обычное 8 марта в море позитива!

home/2019/03/07/f691c4b6a1cbd3f80a58178e365154ae7438d477.jpg

Создаём собственный игровой контроллер

Источник вдохновения На игровых выставках разработчики Objects in Space показывали демо своей игры с контроллером на кокпите огромного космического корабля. Он был дополнен загорающимися кнопками, аналоговыми приборами, световыми индикаторами состояния, переключателями и т.д… Это сильно влияет на погружение в игру: На сайте игры выложен туториал по Arduino с описанием коммуникационного протокола для подобных контроллеров. Я хочу создать то же самое для своей игры В этом примере я потрачу примерно 40 долларов, чтобы добавить красивые, большие и тяжёлые переключатели на кокпит симулятора гонок. Основные затраты связаны с этими самыми переключателями — если бы я использовать простые переключатели/кнопки, то цена была в два раза ниже! Это настоящее оборудование, способное выдерживать 240 Вт мощности, а я буду пускать по ним только примерно 0,03 Вт. Предупреждение: я решил сэкономить, поэтому оставляю ссылку на дешёвый китайский веб-сайт, где закупаю кучу разных компонентов/инструментов. Один из недостатков покупки компонентов по дешёвке заключается в том, что часто у них нет никакой документации, поэтому в статье я решу и эту проблему.

Два в одном: программируемый по Wi-Fi монитор качества воздуха и стрелочные часы

В свое время мне понравился монитор качества воздуха из публикации Сергея Сильнова «Компактный монитор домашнего воздуха (CO2, температура, влажность, давление) с Wi-Fi и мобильным интерфейсом». В мониторе качества воздуха (далее – монитор) из проекта Сергея информация с датчиков температуры, влажности, давления, содержания СО2 в воздухе обрабатывается контроллером ESP8266 и отображается на монохромном экране несколькими кадрами. Кроме того, в мониторе через форму в браузере сохраняется в памяти ESP8266 ключ идентификации сервиса Blynk и автоматически отправляются данные на Blynk. Монитор имел одну серьезную проблему: он зависал на стартовом кадре при выключении-включении или даже «промигивании» напряжения питания монитора. Я повторил проект с несущественными изменениями, а для устранения зависаний монитора добавил в схему альтернативное питание. Простое, как грабли: обмотка реле находилась под напряжением адаптера AC/DC, а его контакты переключали питание с адаптера на батарейки, когда исчезало напряжение в сети 220В. Мой мнимый успех продержался до первого длительного отключения электроэнергии в доме (у нас такое бывает). Дешевые батарейки разрядились раньше, чем появилось напряжение в розетках, а я вернулся к отправной точке. После фальстарта, я решил не искать простых решений.

Book Review: Serious Python

No Starch Press asked me to do a technical review of one of their upcoming books, “Serious Python: Black-Belt Advice on Deployment, Scalability, Testing, and More” by Julien Danjou last year. I had never worked with No Starch before, but decided to give them a try and see how they differed from Packt Publishing. I ended up liking their process and the book was fun to read as well. It should be noted that No Starch did not ask me to do a book review. They only wanted me to do a technical review for them before the book was published. I am writing this review because I think this book should get a little bit more notice. Also I interviewed its author a few years ago, so you might want to check that out too. Quick Review Why I picked it up: Originally, the publisher asked me to do a technical review Why I finished it: The book covers intermediate level material and has an engaging writing style I’d give it to: Beginners that want to grow beyond just knowing Python’s syntax Continue reading Book Review: Serious Python →

Older Posts