Planet Python

Subscribe to Planet Python feed
Planet Python - http://planetpython.org/
Updated: 1 day 34 min ago

TechBeamers Python: Convert Python Strings to Integers Using int(), float(), eval(), Ast, Map(), and More

Sun, 2023-12-24 09:54

Working with strings and integers is a fundamental aspect of programming in Python. There are various scenarios where you may need to convert strings to integers, such as user input, file parsing, or data manipulation. In this tutorial, we will explore different methods to convert Python strings to integers, along with detailed examples for each […]

The post Convert Python Strings to Integers Using int(), float(), eval(), Ast, Map(), and More appeared first on TechBeamers.

Categories: FLOSS Project Planets

Brett Cannon: Introducing basicenum

Sun, 2023-12-24 00:44

In the summer of 2022, my partner was taking her machine learning course as part of UBC&aposs Key Capabilities in Data Science certificate. I was Andrea&aposs on-call tutor for any Python questions, so while Andrea was listening to lectures I decided to do a small project that I thought I could complete during the course.

At the time, the Python steering council had received a couple of asks on backwards-compatibility related to the enum module. I had also been told anecdotally that the enum module didn&apost perform fast enough for some to want to use it (typically around import costs). I had a look at the source code and noticed it was over 2000 lines long and used sys._getframe(). Obviously the enum module has multiple classes and such with a lot of subtle details to it, so it isn&apost necessarily a small API, but the use of sys._getframe() made me want to see if I could replicate API for enum.Enum in less code.

In the end, I got most of the API implemented in less than 200 lines via basicenum.compat.Enum. I couldn&apost get type(enum.variant) and restricted subclassing to work, but I managed to get everything else working (that I can think of; as I said, the API is surprisingly subtle). And according to benchmarking, creation – and thus importing – is way faster, while enum variant access and comparison – i.e. attribute access and equality – are the same.

The really tricky bit with this whole endeavour, though, is typing. Enums are special-cased by type checkers. And while @typing.dataclass_transform() exists to help make dataclass-like packages be treated like dataclass itself, no such decorator exists for enums. As such, you effectively have to lie to the type checkers that basicenum.compat.Enum is equivalent to enum.Enum during type checking:

from typing import TYPE_CHECKING if TYPE_CHECKING: from enum import Enum, auto else: from basicenum.compat import Enum, auto

Have type checkers check against enum while execution uses basicenum.compat

As long as you don&apost rely on type(enum.variant) to be the same as how enum.Enum works, this trick should work (once again, assuming I didn&apost miss anything).

I honestly don&apost have any further plans for this package. While I namespaced things such that if I decided to create an enum type that wasn&apost compatible with enum.Enum to see how simple and/or fast I could make it I could without people getting confused as to what enum type is which, I have no plans to pursue that idea. But it was at least a fun challenge to see if I could at least pull off my goal of re-implementing most of enum.Enum.

Categories: FLOSS Project Planets

James Bennett: Compare strings the right way

Sat, 2023-12-23 16:14

This is part of a series of posts I’m doing as a sort of Python/Django Advent calendar, offering a small tip or piece of information each day from the first Sunday of Advent through Christmas Eve. See the first post for an introduction.

Unicode’s unique complexity

It is the year 2023 — almost 2024! — and hopefully you’re using a programming language that is fully Unicode-aware. Python is; its string type is a sequence of …

Read full entry

Categories: FLOSS Project Planets

CodersLegacy: Pyinstaller EXE detected as Virus? (Solutions and Alternatives)

Sat, 2023-12-23 09:41

PyInstaller, a popular tool for converting Python scripts into standalone executables, has become a go-to choice for developers seeking to distribute their applications. However, a rising concern among users revolves around their PyInstaller EXE files being detected and flagged as a Virus by Antivirus software.

In this article, we’ll delve into the reasons behind this phenomenon and explore various strategies to address and overcome the challenges posed by antivirus detections.

Table Of Contents
  1. Why is your Pyinstaller EXE detected as a Virus?:
  2. Testing with VirusTotal:
  3. Solutions: Pyinstaller EXE detected as Virus
  4. 6. Submit a report to the Antivirus Organization
  5. Conclusion
Why is your Pyinstaller EXE detected as a Virus?:

Before delving into solutions, it’s crucial to understand why PyInstaller-generated EXE files might trigger antivirus alerts. It has little to do with your actual code, as even the most simplest of programs will end up being flagged. In reality, there are many other external factors at play.

  • Due to the popularity and widespread usage of Python, it is not uncommon for hackers or cyber-criminals to distribute malware, trojans, and ransomware using Python + PyInstaller. This is the first issue, as anti-viruses will see similarities between the EXE’s generated by you, and by the malware produced by criminals.

  • Whenever you download an executable from somewhere, you might have seen a popup that asks you if you are sure you want to run the file. You may also see some publisher information in the popup, or a warning message if there is an unknown publisher. When you, as an individual publish an EXE (doesn’t matter what technique you used to make the EXE), you are effectively a stranger in the Anti-virus’s eyes. You have no identity, or authenticity.


It is usually a combination of several of these different reasons that your pyinstaller program will get detected as a virus or malware. We will discuss how to mitigate some (if not all) of these problems in this article, which will hopefully be enough to pass undetected through any anti-virus.

Testing with VirusTotal:

One effective way to ascertain whether your PyInstaller-generated EXE is being detected as a Virus by popular antivirus software is to use the virustotal website. Virustotal allows you to upload your file and scans it with multiple antivirus engines, and lets you know which ones have flagged your EXE as a Virus/Malware, and what warning they have raised.

This website also serves as a good point of reference. Before you begin applying any of the techniques in this article, go and check your EXE by uploading it into the site. Note down how many antiviruses are detecting your EXE as harmful.

Then as you apply each solution, one by one, keep rechecking to see whether there was any improvement.

Solutions: Pyinstaller EXE detected as Virus

A list of solutions for how to avoid your application being flagged by an antivirus. If you have any suggestions, let us know in the comments section, and we will add them to this list.


1. Avoid onefile Mode:

Explanation:
Using PyInstaller’s onefile mode compiles the Python interpreter, your script, and all dependencies into a single compressed executable. This compression can trigger false positives in antivirus scans due to the executable’s compressed nature.

Steps:

  1. Open your terminal or command prompt.
  2. Navigate to your project directory.
  3. Instead of using --onefile in your PyInstaller command, opt for a bundled directory structure by excluding the --onefile option. You can also manually specify the directory mode by using the --onedir option.
2. Build the PyInstaller Bootloader Yourself:

Explanation:
Building the PyInstaller bootloader from source allows you to create a customized version, reducing the likelihood of triggering antivirus alerts. By default, PyInstaller comes with pre-compiled bootloader binaries for different Operating Systems. By compiling the bootloader on your own system, you make the process more consistent (and unique) potentially avoiding patterns that resemble malicious software.

Steps:

  1. Delete any existing PyInstaller related files from your project, such as the build, dist, and __pycache__ folders.
  2. Uninstall PyInstaller using the command: pip uninstall pyinstaller.
  3. Download and Install a C/C++ compiler (if you don’t already have one). For Windows Users, the easiest way of doing this (with very little manual work required) is to download the Visual Studio C/C++ compiler.
  4. Clone the PyInstaller repository from GitHub, or download it as a Zip file. Extract the contents of the folder, and place them in the directory where you want PyInstaller to be installed.
  5. Navigate to the bootloader subdirectory in the PyInstaller folder.
  6. To compile the bootloader, run the following command: python ./waf all (If this command doesn’t work, refer to this documentation page for PyInstaller which explains how to compile the bootloader in detail).
  7. Now go (cd) into the folder you created (or chose) for installing PyInstaller, and run the following command: python.exe setup.py install
  8. Now rebuild your EXE using your new PyInstaller library.
  9. Upload the newly created EXE to the virustotal website to check if there was any improvement.
3. Code Signing Certificate:

Explanation:
Obtaining a code signing certificate is a proactive measure to establish the legitimacy of your application. Code signing involves digitally signing your executable with a certificate issued by a trusted certificate authority (CA). This enhances the trustworthiness of your application and reduces the likelihood of triggering antivirus detections.

Steps:

  1. Obtain a code signing certificate from a trusted certificate authority. Here is a list of certificate providers that Microsoft recommends.
  2. Sign your PyInstaller-generated executable using a tool like signtool or integrated signing options in your development environment.
4. Use Nuitka as an Alternative

Explanation:
Nuitka, an alternative to PyInstaller, takes a different approach by converting Python scripts into optimized C code before compilation. This process results in executables that may have a lower chance of triggering antivirus alerts, making it a viable alternative for developers facing persistent issues with PyInstaller. Nuitka has much of the same features as PyInstaller, such as onefile mode. On top of all this, Nuitka is also faster and more secure than PyInstaller. Only downside is the extra time taken for compiling, as it involves multiple stages (convert to C, then compile).

Steps:

  1. Install Nuitka using the recommended method for your operating system. This can be done using the command pip install nuitka.
  2. Compile your Python script using the Nuitka compiler using the command: python -m nuitka --standalone yourfile.py
  3. Distribute the generated executable to users.

For a more detailed tutorial on Nuitka, and how to customize it, refer to this guide.

5. Utilize Inno Setup or Similar Tools:

Explanation:
Packaging your application with tools like Inno Setup provides a workaround to antivirus detection by creating a more traditional installer. This method avoids direct reliance on PyInstaller’s executable and may reduce the likelihood of false positives. If your application is getting flagged before it even gets to run, this solution will most likely help (as the Inno Setup created EXE is more trustworthy).

Steps:

  1. Download and install Inno Setup or a similar packaging tool.
  2. Follow the script wizard which Inno Setup will prompt you with to create a configuration script for your application. This is fairly easy to follow along with.
  3. Include your PyInstaller-generated executable and dependencies in the installer package (part of the script wizard process).
  4. Compile the script to generate a distributable installer for your application.

If you need a detailed guide with screenshots of all steps, here is a link to our Inno Setup Guide.

6. Submit a report to the Antivirus Organization

Explanation:
Many antivirus software come with a reporting feature, which allow you to report false positives. They will then review your application, and update their virus definitions based on the report. If there is a particular antivirus which is causing you trouble, this will be a good option.

Steps:

  1. Use the virustotal website to determine which antiviruses are flagging your application.
  2. Use the report feature (if available) to have your application greenlit.
Conclusion

Whether through adjusting PyInstaller settings, exploring alternative compilation tools like Nuitka, utilizing packaging tools like Inno Setup, or purchasing code signing certificates, developers have a range of strategies to overcome antivirus detection hurdles and ensure their applications reach users seamlessly. All you need is a little effort (or lots of money!)

This marks the end of the “Pyinstaller EXE detected as Virus?” Article. Any questions about the article content can be asked in the comments section below.

The post Pyinstaller EXE detected as Virus? (Solutions and Alternatives) appeared first on CodersLegacy.

Categories: FLOSS Project Planets

Peter Hoffmann: Exploring Mountain Huts with SPARQL and Wikidata

Fri, 2023-12-22 19:00

For outdoor enthusiasts and avid hikers, searching for mountain huts or shelters is a common thing in tour planning. In this blog post, we'll embark on a journey to retrieve information about mountain huts around a specific latitude and longitude using the powerful combination of SPARQL and Wikidata.

Understanding SPARQL:

SPARQL (SPARQL Protocol and RDF Query Language) is a query language designed for querying data stored in Resource Description Framework (RDF) format. RDF provides a standardized way of representing information, making it an ideal choice for querying diverse datasets.

Accessing Wikidata:

Wikidata, a collaborative knowledge base, hosts a wealth of information on various topics, including geographical features like mountain huts. By employing SPARQL queries on the Wikidata platform, we can extract specific details about these huts based on their geographic coordinates.

Retrieving Mountain Huts:

Let's delve into a SPARQL query to retrieve information about mountain huts around a given latitude and longitude. The following query can be used as a starting point:

SELECT DISTINCT ?distance ?place ?placeLabel ?lat ?long ?elevation WHERE { SERVICE wikibase:around { # Looking for items with coordinate locations(P625) ?place wdt:P625 ?location . # That are in a circle with a centre of with a point bd:serviceParam wikibase:center "Point(8.114444,46.521944)"^^geo:wktLiteral . # Where the circle has a radius of km bd:serviceParam wikibase:radius "10" . bd:serviceParam wikibase:distance ?distance . } ?place p:P625 ?coordinataes . ?coordinataes psv:P625 [ wikibase:geoLatitude ?lat; wikibase:geoLongitude ?long ] . ?place wdt:P31 ?subclassOf . # bivouac shelter (Q879208) or mountain hut (Q182676) VALUES ?subclassOf { wd:Q879208 wd:Q182676} . # Use the label service to get the label with fallback languages SERVICE wikibase:label { bd:serviceParam wikibase:language "de,ch,en,fr,it" . } OPTIONAL { ?place wdt:P2044 ?elevation. } } ORDER BY ?distance

Replace "LONGITUDE" and "LATITUDE" in the query with the desired coordinates. This query retrieves mountain huts within a specified radius (in this example, 10 kilometers) of the given location.

You can also search around a wikidata location by setting the wikdidata id (eg Q68103 Interlaken) as a reference:

wd:Q68103 wdt:P625 ?mainLoc . # Use the around service SERVICE wikibase:around { # Looking for items with coordinate locations(P625) ?place wdt:P625 ?location . # That are in a circle with a centre of ?mainLoc(The coordinate location) bd:serviceParam wikibase:center ?mainLoc . # Where the circle has a radius of km bd:serviceParam wikibase:radius "40" . }

To try it out just copy/past the example into https://query.wikidata.org

You can use the python library SPARQLWrapper to retrieve the results via an api in Json format:

from SPARQLWrapper import SPARQLWrapper, JSON import json query = user_agent = "python test" endpoint_url = "https://query.wikidata.org/sparql" sparql = SPARQLWrapper(endpoint_url, agent=user_agent) sparql.setQuery(query) sparql.setReturnFormat(JSON) result = sparql.queryAndConvert()['results']['bindings'] print(json.dumps(result, indent=4))
Categories: FLOSS Project Planets

James Bennett: Set cookies the right way

Fri, 2023-12-22 14:30

This is part of a series of posts I’m doing as a sort of Python/Django Advent calendar, offering a small tip or piece of information each day from the first Sunday of Advent through Christmas Eve. See the first post for an introduction.

Cookies in the cookie jar

Django’s request and response objects, and their attributes and methods, make dealing with cookies easy. You can read from the request.COOKIES dictionary to get a cookie, and …

Read full entry

Categories: FLOSS Project Planets

PyCharm: Django vs FastAPI: Which is the Best Python Web Framework?

Fri, 2023-12-22 10:02
Introduction If you’re new to web development and have only recently heard of “Frameworks” as a method of speeding up your application development, then you’re in the right place. Today, we’ll explore the two most popular web frameworks in the Python ecosystem currently, namely Django and FastAPI. In this blog post, we’ll help you understand […]
Categories: FLOSS Project Planets

Real Python: The Real Python Podcast – Episode #184: PyCoder's Weekly 2023 Wrap Up

Fri, 2023-12-22 07:00

It's been a fascinating year for the Python language and community. PyCoder's Weekly included over 1,500 links to articles, blog posts, tutorials, and projects in 2023. Christopher Trudeau is back on the show this week to help wrap up everything by sharing some highlights and Python trends from across the year.

[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]

Categories: FLOSS Project Planets

CodersLegacy: Selenium: How to scroll to the Bottom of the Page (Python)

Fri, 2023-12-22 02:54

In this tutorial, we will explore how to use Selenium in Python to scroll to the bottom of a webpage gradually. Scrolling is often required when dealing with dynamically loading content or capturing data from a website that requires scrolling to access all information.

Common examples of such sites are YouTube (shorts) where videos are generated as you scroll down. Another example is e-commerce sites which display alot of products, and use lazy-loading on their images (to load the images only as you scroll down to them).

Many such sites exist, hence learning how to automate scrolling is necessary.

Prerequisites

Before you begin, make sure you have Python and the necessary packages installed. You can install the required packages using the following:

pip install selenium webdriver_manager Setting up Selenium with ChromeDriver

First, let’s set up Selenium with ChromeDriver. We’ll use webdriver_manager to automatically download and manage the ChromeDriver executable (Follow the link to learn how to use this module for the other browsers).

from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.chrome.service import Service as ChromeService from selenium import webdriver import time # Set up ChromeDriver service = ChromeService(executable_path=ChromeDriverManager().install()) driver = webdriver.Chrome(service=service)

Next, we load up the webpage we wish to scrape (or automate). We will be using Wikipedia as an example, as its main page is usually lengthy enough to demonstrate the scroll effect.

driver.get("https://en.wikipedia.org/wiki/Main_Page")

You may replace this with any other URL. The scrolling technique we will learn in this tutorial is not url-specific.

Scrolling Down Gradually

Now, let’s define a JavaScript function to scroll down gradually. This function will be executed using the execute_script function, which takes JavaScript code as a parameter in the form of a string.

= scrollHeight; if (!reachedBottom) { setTimeout(scroll, scrollInterval); } } scroll(); } scrollToBottom(); """ driver.execute_script(scroll_script) driver.quit()" style="color:#d8dee9ff;display:none" aria-label="Copy" class="code-block-pro-copy-button">scroll_script = """ function scrollToBottom() { var scrollHeight = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight); var scrollStep = 200; // Adjust this value to control the scroll speed var scrollInterval = 100; // Adjust this value to control the scroll interval function scroll() { window.scrollBy(0, scrollStep); var reachedBottom = window.innerHeight + window.scrollY >= scrollHeight; if (!reachedBottom) { setTimeout(scroll, scrollInterval); } } scroll(); } scrollToBottom(); """ driver.execute_script(scroll_script) driver.quit()

Adjust the values of scrollStep and scrollInterval to control the scroll speed and interval between scrolls, respectively. If your internet connection is slow, or the website is heavy/slow, you may want to reduce the scroll speed (by lowering interval and scroll step) so that the site loads alongside the scroll.

This code may seem a little complicated, but just remember there is only one “core” line of code here, the window.scrollBy function.

window.scrollBy(0, scrollStep)

This function is responsible for the actual “scrolling”. The rest of the code is simply built around this line, to ensure we don’t scroll beyond the limit of the page. The window object contains useful information about the page which can be used to determine when we have reached the end.

= scrollHeight;" style="color:#d8dee9ff;display:none" aria-label="Copy" class="code-block-pro-copy-button">var reachedBottom = window.innerHeight + window.scrollY >= scrollHeight;

The above line is an expression which evaluates to True if we have reached the bottom of the page. It is calculated by checking if the sum of the current viewport height and scroll position is equal to or greater than the total scrollable height.

This marks the end of the Selenium Tutorial on How to scroll to the Bottom of the Page. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.

The post Selenium: How to scroll to the Bottom of the Page (Python) appeared first on CodersLegacy.

Categories: FLOSS Project Planets

Brett Cannon: Announcing microvenv 2023.5

Thu, 2023-12-21 19:56

In my blog post explaining how virtual environments work, I announced my project called microvenv. At the time, my only goal was to create a package which could create virtual environments in a minimal, fast way. But since then, I have expanded the API of the package to provide some helpers I found myself and teammates at work needing. I also updated it to match a change coming to the venv module in Python 3.13.

Expanded API

Probably the newest part I&aposm most happy about is the activation() function which helps you "activate" your virtual environment. Normally when you run the shell script to activate your virtual environment, it sets the VIRTUAL_ENV environment variable and prepends the bin/ directory to PATH. The activation() function does this, but in a way designed to be additive to os.environ. What this means is the API is designed to be typically used as os.environ | microvenv.activation(). Because the union operator for dicts has the right-hand side take precedence, the updated value of PATH will mask the one from os.environ while adding VIRTUAL_ENV. And because | for dictionaries returns a new dict, you don&apost need to worry about deactivation as no in-place mutation of os.environ occurs.

There&aposs also now a parse_config() function to parse the pyvenv.cfg file into a dict. The file is a custom format of key/value pairs that looks like an INI file with no section headers. Historically, people have parsed this file by adding a fake header via configparser and then parsing the file. But if you look at the code in the site module that actually processes the file, you will notice it doesn&apost use the configparser. As such, I wrote a function that uses the same algorithm to make it easier to get to.

I also tossed in IN_VIRTUAL_ENV and DEFAULT_ENV_DIR constants to detect when you&aposre running from a virtual environment and the default name to use when creating a virtual environment, respectively.

.gitignore file in virtual environments

Starting in Python 3.13, virtual environments will contain a .gitignore file containing the text of * by default, and I have updated microvenv accordingly. This will cause Git to ignore the virtual environment directory. We did this because we regularly found beginners committing their virtual environments to source control without realizing that virtual environments are not portable between machines. We also view virtual environment contents as essentially an implementation detail, and so you shouldn&apost put your code in there as we reserve the right to do whatever we want in there which might clash with your files some day.

Miscellaneous

The project is now fully typed via .pyi files (due to wanting to keep the _create.py file as small as possible). Also, the project is now a package to once again keep _create.py small.

Categories: FLOSS Project Planets

James Bennett: Don't use Python's property

Thu, 2023-12-21 17:32

This is part of a series of posts I’m doing as a sort of Python/Django Advent calendar, offering a small tip or piece of information each day from the first Sunday of Advent through Christmas Eve. See the first post for an introduction.

Attributing the problem

Suppose you’re writing Java and you write a class with an attribute :

public class MyClass { public int value; }

And then later on you realize that value …

Read full entry

Categories: FLOSS Project Planets

TestDriven.io: Basic and Full-text Search with Django and Postgres

Thu, 2023-12-21 17:28
This tutorial looks at how to add basic and full-text search to a Django app with Postgres.
Categories: FLOSS Project Planets

PyCharm: PyCharm 2023.3.2 Is Out!

Thu, 2023-12-21 08:40

The second bug-fix update for v2023.3 is now available.

You can update to this version from inside the IDE, using the Toolbox App, or using snaps if you are a Ubuntu user. You can also download it from our website.

Here are the most notable fixes and updates that PyCharm 2023.3.2 brings:

  • PyCharm now correctly resolves <code>pytest_plugins</code> for pytest fixtures declaration. [PY-62419]
  • The test runner now works fine with Django 5.0. [PY-53355]
  • We’ve fixed several issues that were cropping up when working with the HTTP Client. [IDEA-332986IDEA-224825IDEA-296844]
  • We’ve fixed the issue causing the IDE to display a blank window when opening a second project in full-screen mode on macOS. [IDEA-339992]
  • When using borderless mode on Windows, the IDE once again correctly restores the position of a window that had previously been snapped to one side of the screen. [IDEA-250563]
  • We’ve fixed the issue causing the IDE to crash on startup due to errors appearing when parsing the UI theme. [IDEA-340108]
  • The main menu is displayed for all open projects on the tiling desktop when working on Linux. [IDEA-328047]
  • The IDE no longer erroneously resets namespaces during actions like ApplyRefresh, and others when working with Kubernetes. [IDEA-339448]  
  • The branch checkout from the Pull Request pane has been fixed. [IDEA-339471
  • When you work on Linux without a window manager, the main menu is now displayed for all open projects. [IDEA-337548]

For more information about the issues we’ve addressed, please refer to the release notes

If you experience any other issues, please report them to our issue tracker.

Categories: FLOSS Project Planets

Doug Hellmann: virtualenvwrapper 6.0.0.0a5

Thu, 2023-12-21 06:54
What’s new in 6.0.0.0a5? move build dependencies to pyproject.toml move linter dependencies to pyproject.toml Improve error message for IOErrors (contributions by Fabian P. Schmidt) add python 3.12 to test matrix Fix shell completion on FreeBSD (contributions by bendikro) Fixed broken link in install docs. (contributions by Carlton Gibson) install setuptools for test packages, use pip (contributions by Alfred Wingate) remove use of distutils (contributions by Alfred Wingate) Update the tested Python versions to match README (contributions by Evan Chong) Changed workon’s env switching to use OR not $?
Categories: FLOSS Project Planets

Doug Hellmann: sphinxcontrib-datatemplates 0.11.0

Thu, 2023-12-21 04:59
What’s new in 0.11.0? handle file exceptions when loading data or templates (contributions by Bizordec)
Categories: FLOSS Project Planets

Hynek Schlawack: Don’t Start Pull Requests from Your Main Branch

Thu, 2023-12-21 00:00

When contributing to other users’ repositories, always start a new branch in your fork.

Categories: FLOSS Project Planets

James Bennett: Use Django's system checks

Wed, 2023-12-20 19:41

This is part of a series of posts I’m doing as a sort of Python/Django Advent calendar, offering a small tip or piece of information each day from the first Sunday of Advent through Christmas Eve. See the first post for an introduction.

Check it out

While you can do very minimal Django setups, more typical use cases tend to involve a mix of applications — your own, some third-party, and some from django.contrib — …

Read full entry

Categories: FLOSS Project Planets

Matt Layman: Sign Up - Building SaaS with Python and Django #178

Wed, 2023-12-20 19:00
In this episode, we did some work on the sign up template. In the process, we added some base template styling, talked about branding, and considered the other elements that are required before we can turn on sign up for others. I also cover waffle as a feature flag tool.
Categories: FLOSS Project Planets

Real Python: Add Logging and Notification Messages to Flask Web Projects

Wed, 2023-12-20 09:00

After implementing the main functionality of a web project, you may find that your app is rough around the edges. Often, this boils down to the user experience (UX) of your project. For example, when you send a form, you don’t receive a success message, although everything worked fine. You want to build an immersive experience, but wrong URLs display unwelcoming error messages. Luckily, you can get valuable information from Flask through logging.

As an admin of a web project, you may know how to navigate your app without running into errors. But looking at the messages that the server sends you, you may notice that not all users do. That’s when a more verbose logging system can give you insights.

In this tutorial, you’ll learn how to:

  • Create error pages
  • Improve the user experience with notification messages
  • Gain information with logging

Adding features like the ones listed above may keep your current functionality intact and enhance your web project with a better user experience that your visitors will love.

Get Your Code: Click here to download the free source code that shows you how to add error pages and logging to your Flask app.

Prerequisites

You’ll gain the most value from this tutorial if you’ve already created one or more Flask web projects yourself. It’ll also be helpful if you’ve worked with Jinja templating and HTML and CSS before.

Also, you should be comfortable using the terminal and have basic knowledge of Python. Although it helps to know about virtual environments and pip, you’ll learn how to set everything up as you work through the tutorial.

Project Overview

In this tutorial, you’ll continue to work on an existing Flask project. The project at hand is a public message board.

You’ll start with an existing Flask project and then implement logging and notification messages:

The demo video above shows the Flask project on the left and the terminal with server logs on the right. When you interact with the web app, you get helpful feedback with notification messages. As an admin, you can also see the info messages in your logs to help you understand how your users interact with your app.

In the next step, you’ll download the source code of the Flask project. However, you’ll notice that the codebase is quite generic so that you can transfer the instructions of this tutorial into your own Flask project.

Get Started

In this section, you’ll download all the requirements that you need for this tutorial and set up the development environment. Generally, you can leverage this tutorial to expand any Flask project that you’re currently working on. However, if you want to follow along closely, then you should perform the steps outlined below.

Grab the Prerequisites

To hit the ground running, you’ll build up on an existing Flask project with a database. That way, you don’t need to create a Flask project from scratch. Instead, you can focus on the main objectives of this tutorial, like adding an error page and displaying helpful messages to your users.

The code that you need is already in place for you. All you need to do is download the source code by clicking the link below:

Get Your Code: Click here to download the free source code that shows you how to add error pages and logging to your Flask app.

Alternatively, you can follow the Flask project with a database tutorial. Either way, you should end up with a folder structure that looks like this:

rp_flask_board/ ├── board/ │ │ │ ├── static/ │ │ └── styles.css │ │ │ ├── templates/ │ │ │ │ │ ├── pages/ │ │ │ ├── about.html │ │ │ └── home.html │ │ │ │ │ ├── posts/ │ │ │ ├── create.html │ │ │ └── posts.html │ │ │ │ │ ├── _navigation.html │ │ └── base.html │ │ │ ├── __init__.py │ ├── database.py │ ├── pages.py │ ├── posts.py │ └── schema.sql │ └── board.sqlite

Once you’ve got the folder structure for your Flask project in place, you can read on to prepare the development environment that you’ll need to work on your web app.

Prepare Your Development Environment Read the full article at https://realpython.com/flask-logging-messages/ »

[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]

Categories: FLOSS Project Planets

Python Bytes: #365 Inheritance, but not Inheritance!

Wed, 2023-12-20 03:00
<strong>Topics covered in this episode:</strong><br> <ul> <li><em>* <a href="https://hatch.pypa.io/latest/blog/2023/12/11/hatch-v180/">Hatch v1.8</a></em>*</li> <li><a href="https://svcs.hynek.me/en/stable/">svcs: A Flexible Service Locator for Python</a></li> <li><a href="https://discuss.python.org/t/steering-council-election-results-2024-term/40851">Steering Council 2024 Term Election Results</a></li> <li><a href="https://typethepipe.com/post/python-protocols-when-to-use">Python protocols. When to use them in your projects to abstract and decoupling</a></li> <li><strong>Extras</strong></li> <li><strong>Joke</strong></li> </ul><a href='https://www.youtube.com/watch?v=x2X0GVX9624' style='font-weight: bold;'>Watch on YouTube</a><br> <p><strong>About the show</strong></p> <p>Sponsored by us! Support our work through:</p> <ul> <li>Our <a href="https://training.talkpython.fm/"><strong>courses at Talk Python Training</strong></a></li> <li><a href="https://courses.pythontest.com/p/the-complete-pytest-course"><strong>The Complete pytest Course</strong></a></li> <li><a href="https://www.patreon.com/pythonbytes"><strong>Patreon Supporters</strong></a></li> </ul> <p><strong>Connect with the hosts</strong></p> <ul> <li>Michael: <a href="https://fosstodon.org/@mkennedy"><strong>@mkennedy@fosstodon.org</strong></a></li> <li>Brian: <a href="https://fosstodon.org/@brianokken"><strong>@brianokken@fosstodon.org</strong></a></li> <li>Show: <a href="https://fosstodon.org/@pythonbytes"><strong>@pythonbytes@fosstodon.org</strong></a></li> </ul> <p>Join us on YouTube at <a href="https://pythonbytes.fm/stream/live"><strong>pythonbytes.fm/live</strong></a> to be part of the audience. Usually Tuesdays at 11am PT. Older video versions available there too.</p> <p><strong>Michael #1: <a href="https://hatch.pypa.io/latest/blog/2023/12/11/hatch-v180/">Hatch v1.8</a></strong></p> <ul> <li>Hatch now manages installing Python for you.</li> <li>Hatch can build .app and .exe stand-alone binaries for you</li> <li>The macOS ones are signed (signed!)</li> <li>Discussion <a href="https://discuss.python.org/t/announcement-hatch-v1-8-0/40865">here</a></li> </ul> <p><strong>Brian #2:</strong> <a href="https://svcs.hynek.me/en/stable/">svcs : A Flexible Service Locator for Python</a></p> <ul> <li>Hynek</li> <li>A library to help structure and test Python web applications.</li> <li>“<em>svcs</em> (pronounced <em>services</em>) is a <strong>dependency container<em>* for Python. It gives you a central place to register factories for types/interfaces and then imperatively acquire instances of those types with </em><em>automatic cleanup</em>* and **health checks</strong>.”</li> <li>“Benefits: <ul> <li>Eliminates tons of repetitive <strong>boilerplate</strong> code,</li> <li>unifies <strong>acquisition<em>* and </em><em>cleanups</strong> of services,</li> <li>provides full <em>static</em> <strong>type safety</strong> for them,</li> <li>simplifies <strong>testing<em></em> through </em><em>loose coupling</strong>,</li> <li>improves <em>live</em> <strong>introspection<em></em> and </em><em>monitoring</em>* with **health checks</strong>.”</li> </ul></li> <li>Hynek has started a <a href="https://www.youtube.com/watch?v=d1elMD9WgpAhttps://www.youtube.com/watch?v=d1elMD9WgpA">YouTube channel, and is starting with an explanation of svcs.</a></li> <li>Yes, Hynek, we want more videos. I like that it’s not a beginner level. </li> <li>My request for future videos: just past beginner, and also intermediate level.</li> <li>There are plenty of basics videos out there, not as many filling the gaps between beginner and production.</li> </ul> <p><strong>Michael #3:</strong> <a href="https://discuss.python.org/t/steering-council-election-results-2024-term/40851">Steering Council 2024 Term Election Results</a> </p> <ul> <li>The 2024 Term Python Steering Council is: <ul> <li>Pablo Galindo Salgado</li> <li>Gregory P. Smith</li> <li>Emily Morehouse</li> <li>Barry Warsaw</li> <li>Thomas Wouters</li> </ul></li> <li>Full results are available in <a href="https://peps.python.org/pep-8105/#results">PEP 8105</a> .</li> <li>How do you become a candidate? <ul> <li>Candidates must be nominated by a core team member. If the candidate is a core team member, they may nominate themselves.</li> </ul></li> </ul> <p><strong>Brian #4:</strong> <a href="https://typethepipe.com/post/python-protocols-when-to-use">Python protocols. When to use them in your projects to abstract and decoupling</a></p> <ul> <li>Carlos Vecina</li> <li>“Protocols are an alternative (or a complement) to inheritance, abstract classes and Mixins.”</li> <li>Understanding interactions between ABC, MixIns and Protocols in Python</li> <li>With examples</li> </ul> <p><strong>Extras</strong> </p> <p>Brian:</p> <ul> <li>Donations. It’s a decent time of the year to donate to projects that help you <ul> <li><a href="https://www.python.org/psf/donations/2023-q4-drive/">Python Software Foundation</a></li> <li><a href="https://www.djangoproject.com/fundraising/">Django Software Foundation</a></li> <li><a href="https://www.patreon.com/pythonbytes">Python Bytes</a></li> <li>Also, look for “Sponsor this project” links in GitHub for projects you depend on.</li> </ul></li> </ul> <p>Michael:</p> <ul> <li><strong>Mastodon guidelines</strong> (mine): <ul> <li>If you have a picture and description, I’ll probably follow you back</li> <li>If you have posts that seem relevant +1</li> <li>If you have a verified webpage +1</li> <li>If your account is private, won’t. I don’t understand really since private group messages already exist and the profile itself is public.</li> </ul></li> <li>Speaking of Mastodon. I had a productive conversation with the PSF and others around masks and conferences.</li> <li><a href="https://arstechnica.com/information-technology/2023/12/dropbox-spooks-users-by-sending-data-to-openai-for-ai-search-features/">Dropbox spooks users by sending data to OpenAI for AI search features</a> <ul> <li>There was a comment in the above article to the effect of “Once you give your data to a third party (even trusted like Dropbox), you no longer control that data.” That sent me searching and thinking…</li> <li><a href="https://www.sync.com/?_sync_refer=721a76dd0">sync.com</a>? <a href="https://proton.me/drive">proton drive</a> (<a href="https://pr.tn/ref/4SM38ZQPNS3G">discount code</a>)? <a href="https://nextcloud.com">nextcloud</a>? <a href="https://filen.io">filen.io</a>? <a href="https://icedrive.net">icedrive.net</a>?</li> <li>ownCloud’s <a href="https://www.greynoise.io/blog/cve-2023-49103-owncloud-critical-vulnerability-quickly-exploited-in-the-wild">recent CVE</a> makes me a bit nervous of self-hosted options.</li> <li>Either way, <a href="https://cryptomator.org">Cryptomator</a> is very interesting.</li> </ul></li> <li>Beyond privacy, this got me thinking, just how many hours of dev time have been diverted to add mediocre-at-best AI features to everything?</li> <li>I’m doing a big digital decluttering and have lots to say on that soon.</li> <li><strong>Not</strong> submitting my talks to PyCascades this year. </li> <li>But I <strong>did submit</strong> 3 talks to PyCon US. 🤞 </li> <li>I <strong>will</strong> be giving the keynote at <a href="https://pycon-2024.python.ph">PyCon Philippines</a>.</li> </ul> <p><strong>Joke:</strong> <a href="https://mastodon.social/@tveskov/111289358585305218">The dream is dead?</a></p>
Categories: FLOSS Project Planets

Pages