Category Archives: Cross-Platform

This article will be about a topic that can be used across platforms, such as Linux, Windows and Mac.

Flask 101: Filtering Searches and Deleting Data

Last time we got our Flask based music database application partially functional. It could now add data to the database, edit said data and also display everything in the database. But we didn’t cover how to filter the data by using the user’s filter choice (Artist, Album name or publisher name) and search string. We also didn’t cover how to delete items from the database. That is the two-fold goal of this article.


Filtering Search Results

Filtering search results using SQLAlchemy (via Flask-SQLAlchemy) is actually quite easy. All you need to do is create some very simple query objects. Open up the main.py file that we were editing last time and replace the search_results() function with the following version of the code: Continue reading Flask 101: Filtering Searches and Deleting Data

Flask 101: Adding, Editing and Displaying Data

Last time we learned how to add a search form to our music database application. Of course, we still haven’t added any data to our database, so the search form doesn’t actually do much of anything except tell us that it didn’t find anything. In this tutorial we will learn how to actually add data, display search results and edit entries in the database.

Let’s get started!


Adding Data to the Database

Let’s start by coding up our new album form. Open up the “forms.py” file we created in the last tutorial and add the following class:

class AlbumForm(Form):
    media_types = [('Digital', 'Digital'),
                   ('CD', 'CD'),
                   ('Cassette Tape', 'Cassette Tape')
                   ]
    artist = StringField('Artist')
    title = StringField('Title')
    release_date = StringField('Release Date')
    publisher = StringField('Publisher')
    media_type = SelectField('Media', choices=media_types)

This defines all the fields we need to create a new Album. Now we need to open “main.py” and add a function to handle what happens when we want to create the new album. Continue reading Flask 101: Adding, Editing and Displaying Data

Flask 101: How to Add a Search Form

In our last article, we added a database to our Flask web application, but didn’t have a way to add anything to our database. We also didn’t have a way to view anything, so basically we ended up having a pretty useless web application. This article will take the time to teach you how to do the following:

  • Create a form to add data to our database
  • Use a form to edit data in our database
  • Create some kind of view of what’s in the database

Adding forms to Flask is pretty easy too, once you figure out what extension to install. I had heard good things about WTForms so I will be using that in this tutorial. To install WTForms you will need to install Flask-WTF. Installing Flask-WTF is pretty easy; just open up your terminal and activate the virtual environment we set up in our first tutorial. Then run the following command using pip:

pip install Flask-WTF

This will install WTForms and Flask-WTF (along with any dependencies) to your web app’s virtual environment. Continue reading Flask 101: How to Add a Search Form

Flask 101: Adding a Database

Last time we learned how to get Flask set up. In this article we will learn how to add a database to our music data website. As you might recall, Flask is a micro-web-framework. That means it doesn’t come with an Object Relational Mapper (ORM) like Django does. If you want to add database interactivity, then you need to add it yourself or install an extension. I personally like SQLAlchemy, so I thought it was nice that there is a ready-made extension for adding SQLAlchemy to Flask called Flask-SQLAlchemy.

To install Flask-SQLAlchemy, you just need to use pip. Make sure that you are in your activated virtual environment that we created in the first part of this series before you run the following or you’ll end up installing the extension to your base Python instead of your virtual environment:

pip install flask-sqlalchemy

Now that we have the Flask-SQLAlchemy installed along with its dependencies, we can get started creating a database! Continue reading Flask 101: Adding a Database

Flask 101: Getting Started

The Flask 101 series is my attempt at learning the Flask microframework for Python. For those who haven’t heard of it, Flask is micro web framework for creating web applications in Python. According to their website, Flask is based on Werkzeug, Jinja 2 and good intentions. For this series of articles, I wanted to create a web application that would do something useful without being too complicated. So for my learning sanity, I decided to create a simple web application that I can use to store information about my music library.

Over the course of multiple articles, you will see how this journey unfolded.


Getting Setup

To get started using Flask, you will need to install it. We will create a virtual environment for this series of tutorials as there will be a number of other Flask dependencies that we will need to add and most people probably don’t want to pollute their main Python installation with a lot of cruft they may not end up using. So before we install Flask, let’s create a virtual environment using virtualenv. If you want to use virtualenv, then we will need to install that with pip: Continue reading Flask 101: Getting Started

Back to School Python Book Sale 2017

It’s time for school and going back to the university, so I am putting on a “Back to School” sale for my Python books. You can now buy my second and third books for 50% off on Leanpub.

You can check out my first book, Python 101, in its entirety over on http://python101.pythonlibrary.org/ if you need a sample of my writing style. Leanpub also has samples of both of those books that you can download as a PDF.

Feel free to ask questions in the comments or ping me via the contact form.

Python 101: Working with Dates and Time

Python gives the developer several tools for working with dates and time. In this article, we will be looking at the datetime and time modules. We will study how they work and some common uses for them. Let’s start with the datetime module!

The datetime Module

We will be learning about the following classes from the datetime module:

  • datetime.date
  • datetime.timedelta
  • datetime.datetime

These will cover the majority of instances where you’ll need to use date and datetime object in Python. There is also a tzinfo class for working with time zones that we won’t be covering. Feel free to take a look at the Python documentation for more information on that class. Continue reading Python 101: Working with Dates and Time

ANN: Boomslang XML

I recently decided to start putting together some fun example desktop applications using Python. I’ve been using wxPython to create the cross platform applications. My first one is called Boomslang XML and is a basic XML editor.

The name, Boomslang, comes from a large venomous snake. It’s name basically means “tree snake”, which I thought was appropriate since the user interface uses a tree widget to represent the structure of the XML document.

The current features in Boomslang include the following:

  • Opening / Editing multiple XML files
  • Auto save on edit of the XML
  • Recent file support
  • Some keyboard shortcuts (accelerators)
  • Add new XML nodes or attributes
  • Edit nodes and attributes
  • Delete nodes

Currently this is fairly beta, but I thought other people might find it interesting. I am aware of a couple of issues with it currently, such as the inability to delete attributes or not being able to add an XML node with spaces in it But I will get those fixed soon. In the meantime, feel free to check out the project over on Github.

Note: This project was tested with Python 2 and 3, wxPython 2.9, 3.0, and 4.0 using the lxml package on Windows 7, Xubuntu 16.04 and Mac OSX Sierra.

wxPython: Working with Status Bars

Most applications come with the Status Bar. The status bar is the widget along the bottom of most applications that you use every day. They give you information about what line you’re editing in a text editor or when you last saved. In wxPython, you can add a status bar to your frame by using the wx.StatusBar class. In this article, we will learn all about how to use status bars in wxPython.


No Status Bars

It’s always good to start at the beginning. So we will begin our journey by looking at some sample code that shows what a frame looks like without a status bar:

import wx
 
class MainFrame(wx.Frame):
 
    def __init__(self):
        wx.Frame.__init__(self, None, title='No Statusbars')
 
        panel = wx.Panel(self)
 
        self.Show()
 
if __name__ == '__main__':
    app = wx.App(False)
    frame = MainFrame()
    app.MainLoop()

When you run this code, you should see something like the following:

Continue reading wxPython: Working with Status Bars

wxPython: Learning about TreeCtrls

The wxPython GUI toolkit comes with many widgets. A common control is a tree widget. wxPython has several different tree widgets, including the regular wx.TreeCtrl, the newer DVC_TreeCtrl and the pure Python variants, CustomTreeCtrl and HyperTreeList. In this article, we will focus on the regular wx.TreeCtrl and learn the basics of how to create and use one.

Creating a Simple Tree

Creating a TreeCtrl is actually quite easy. The wxPython demo has a fairly complex example, so I wasn’t able to use it here. Instead I ended up taking the demo example and stripping it down as much as I could. Here’s the result:

import wx
 
class MyTree(wx.TreeCtrl):
 
    def __init__(self, parent, id, pos, size, style):
        wx.TreeCtrl.__init__(self, parent, id, pos, size, style)
 
 
class TreePanel(wx.Panel):
 
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
 
        self.tree = MyTree(self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize,
                           wx.TR_HAS_BUTTONS)    
 
        self.root = self.tree.AddRoot('Something goes here')
        self.tree.SetPyData(self.root, ('key', 'value'))
        os = self.tree.AppendItem(self.root, 'Operating Systems')
        self.tree.Expand(self.root)
 
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.tree, 0, wx.EXPAND)
        self.SetSizer(sizer)
 
 
class MainFrame(wx.Frame):
 
    def __init__(self):
        wx.Frame.__init__(self, parent=None, title='TreeCtrl Demo')
        panel = TreePanel(self)
        self.Show()
 
 
if __name__ == '__main__':
    app = wx.App(redirect=False)
    frame = MainFrame()
    app.MainLoop()

In this example, we create a subclass of wx.TreeCtrl that doesn’t do anything. Then we create a panel subclass where we instantiate the tree and add a root and sub-item. Finally we create the frame that holds the panel and run the application. You should end up with something that looks similar to the following:

This is a pretty boring example, so let’s make something a bit more interesting. Continue reading wxPython: Learning about TreeCtrls