Deprecated: Function get_magic_quotes_gpc() is deprecated in /home1/markfrim/public_html/textpattern/lib/constants.php on line 149
Mark Frimston - Articles - Tutorials Where the subheading is false tag:markfrimston.co.uk,2005:b22331e63cd9207172a5123b6a1c69ef/articles/tutorials Textpattern 2018-09-27T11:30:22Z Mark Frimston mfrimston@gmail.com http://markfrimston.co.uk/ Mark Frimston 2014-10-07T18:06:16Z 2015-10-01T15:39:08Z Quick Python Web Setup for Apache tag:markfrimston.co.uk,2014-10-07:b22331e63cd9207172a5123b6a1c69ef/9cc67499a79417049a32500d7885fbb0 Today I wanted to set up a quick web script; just something that ran on the Apache server I already had set up, took some query parameters and spat out a basic page in response. My usual go-to for this kind of thing would typically be PHP, because it's so quick to throw together and deploy. But this time, I wanted to see what the Python equivalent would be. Is it possible to write a quick Python script, drop it on a server and have it just work? Well, yes, it turns out it is. Or very close, at least. Here's how...

Step 1: Get Apache

For the purposes of this tutorial, we're going to use Apache because if you're running PHP, you most likely already have it set up - they're a popular combination. If it isn't already installed, you'll find it in your package repository or there'll be an installer on the website. In Debian-based flavours of Linux, it's a one-liner:

$ sudo apt-get install apache2

To check that Apache is set up, you'll want to visit localhost in your browser (perhaps localhost:8080, depending on the default config), and make sure you're greeted with the "it works!" page, or whatever.

Step 2: Get Python

You'll need the Python interpreter to execute Python scripts. Again, your package manager will almost certainly list it, or else you can find an installer on the Python website. For Debian, it's just:

$ sudo apt-get install python

Step 3: Mod-WSGI

There are a bunch of different ways of using Python for the web, but if you're interested in having your script be compatible with a wide number of different environments, the WSGI standard is the way to go. Short for Web Standard Gateway Interface, this is a spec that was drawn up in 2003 as a standard way for web servers to interface with the Python application running on it. It's been widely adopted by many Python web frameworks, as it allows you to develop a web application that can run on many different web servers.

Mod-WSGI lets us serve WSGI-compatible scripts via Apache, in the same way that Mod-PHP serves PHP scripts. It is likely to be present in your package manager on Linux, but otherwise you will need to follow the installation guide. In Debian, using Python 2, it's:

$ sudo apt-get install libapache2-mod-wsgi

Or for Python 3, make sure you use:

$ sudo apt-get install libapache2-mod-wsgi-py3

Step 4: Write a Script

Writing a WSGI-compatible Python script is as simple as implementing a single function. Here's the basic "Hello World" script that responds with some text:


def application( environment, start_response ):
    start_response( '200 OK', [( 'Content-Type', 'text/plain' )] )
    return [ 'Hello World' ]

We implement a function called application, and this takes 2 parameters. The first parameter is a dictionary of values from the web server. This contains things like the query parameters, the path of the document root, and so on.

The second parameter is a function which we can call to start outputting the response. The first parameter to this function is the HTTP status code, which will be "200 OK" for a successful request. The second parameter is a list of headers to include in the response. In the example above, we just output a single "Content-Type" header to tell the browser to treat the content as plain text.

The return value of this application function must be an iterable containing the response body. The reason for an iterable is simply to make it convenient to build up the response in stages. It allows us to, for example, use a generator instead to yield bits of the response as we go along.

Step 5: Create a Home For Your Web Scripts

Now we need to create a directory to put our web scripts in, so that Apache can find them. Note, this should not be Apache's document root, because if we put a script there Apache will serve up the source code instead of running it.

We'll create the example directory suggested in Mod-WSGI's documentation, but this could be whatever you like:

$ sudo mkdir -p /usr/local/www/wsgi-scripts

You should put your test WSGI script in this directory.

Step 6: Configure Apache

Finally we need to tell Apache how to serve up the WSGI script. Locate your Apache config file. On my Linux setup this was /etc/apache2/apache2.conf, but it can also be typically found at /etc/httpd/httpd.conf. At the bottom of the file, we'll add the following directive. This ensures that Apache can access our scripts directory:

<Directory /usr/local/www/wsgi-scripts>
Order allow,deny
Allow from all
</Directory>

And below this, we must add a directive to tell Apache what URL to map our script to. The first parameter to WSGIScriptAlias is the URL path the application will reside under. The second parameter is the file system path to the script file itself:

WSGIScriptAlias /test /usr/local/www/wsgi-scripts/myscript.wsgi

Depending on your version of Apache, you may need to use Require all granted instead of the Order and Allow lines.

We'll need to restart Apache to make these changes take effect:

$ sudo service apache2 restart

Now, when you visit http://localhost/test you should see the output from the Python script, "Hello World".

Errors

If there is an error in the Python script, Apache will instead report "500: Internal Server Error". The reason for the error can be found in the Apache error log. On my setup this was at /var/log/apache/error.log.

Conclusion

This makes for a fairly straightforward setup that gets you from Python to browser in a minimal number of steps, and in a way that allows you to progress to one of the many WSGI-compatible web frameworks if your script grows in complexity.

It's still not quite as easy to deploy as PHP, as each new script will require a new WSGIScriptAlias directive and a restart of Apache, but it's not bad.

Have fun writing quick web scripts in Python!

]]>
Today I wanted to set up a quick web script; just something that ran on the Apache server I already had set up, took some query parameters and spat out a basic page in response. My usual go-to for this kind of thing would typically be PHP, because it's so quick to throw together and deploy. But this time, I wanted to see what the Python equivalent would be. Is it possible to write a quick Python script, drop it on a server and have it just work? Well, yes, it turns out it is. Or very close, at least. Here's how...

]]>
Mark Frimston 2012-06-26T16:41:12Z 2012-06-26T16:41:12Z Some Features You May Not Know Nano Has tag:markfrimston.co.uk,1969-12-31:b22331e63cd9207172a5123b6a1c69ef/2a6423ee6e345b4521fc01d196ca9482 Nano?

When it comes to text editors in Linux, there are two major players which have famously been causing holy wars for at least a couple of hundred years now: Vi and Emacs. They are both extremely powerful, lightweight editors whose ages are a testament to how useful they have been and continue to be.

If you are already a Vi or Emacs user, then great! If you're not, and you do a lot of code editing under Linux, you should probably consider learning one of them. So, with that in mind, here's another text editor that you may or may not have heard about: GNU Nano.

GNU Nano is a basic command-line text editor which is installed by default with many Linux distributions. Nano is not intended to be anywhere near as feature-rich as Vi or Emacs. It is a very simple tool, but this means it requires little to no time investment to start using for basic file editing tasks. Nano's core commands are easy to learn because they're written out at the bottom of the screen, and files can be navigated intuitively with the cursor keys.

I find nano extremely handy, and it has some neat features that you may not have known about. In this post, I'd like to share some of nano's more hidden capabilities.

Overriding the Default Configuration

Nano has a bunch of features which can be turned on by passing in the appropriate option flag from the command line. For example, the i option enables nano's auto-indent feature:

nano -i

Specifying command line options each time you use the program, however, would quickly become tedious. As an alternative, nano can read a configuration file with settings that will be applied each time it runs. On my Linux distribution, nano's global config file is found in /etc/nanorc. If this file already exists, you will most likely find that it contains example configuration settings which are commented out. Settings in this file are turned on and off with set and unset commands, one per line. Each set or unset is followed by the feature name to switch on or off. For example, the following line would turn on the auto-indent feature every time nano is run:

set autoindent

The global config file defines the default settings for all users of the system. In a multi-user environment, you will want to define settings on a per-user basis instead. Individual users can override the global defaults with their own config file which is read from their home directory at ~/.nanorc. For example, the config file for user dave would be read from /home/dave/.nanorc.

More information on nano's config file can be found in the nanorc man page. With the configuration file covered, let's take a look at what features it can activate.

Multiple File Buffers

Out of the box, nano is configured to use a single file buffer, only. If you try to open a file with ctl+r when you already have one open, the contents of the new file will be appended to the end of the current one. Much more useful is to be able to have multiple files open at once and switch between them. This feature can be enabled with the multibuffer option:

set multibuffer

It can also be turned on and off at runtime with the keyboard command alt+f. With this feature enabled, a newly opened file will be placed in its own buffer. alt+< and alt+> cycle through the open buffers and ctl+x closes a buffer.

Auto Indent

Auto indent is a feature present in many IDEs and is very handy for code editing. Upon inserting a linebreak, instead of positioning the cursor at the start of the new line, the cursor is positioned with the same indentation level as the previous line.

Without auto-indent:

1 |    An indented line ↵
2 |█

With auto-indent:

1 |    An indented line ↵
2 |    █

As mentioned earlier, auto-indent can be enabled by default in your config file with:

set autoindent

And can be turned on and off at runtime with alt+i. One caveat to note here is that you may want to disable this feature just before you copy and paste text from an external source into the editor. This will ensure that auto-indent doesn't try to indent each new line of the pasted text.

Smart Home

Smart home is another feature common to a lot of IDEs. When the home key is pressed on an indented line, the cursor will jump to the start of the indented content rather than the actual start of the line.

Without smart home:

 1 |█    An indented line
 2 |

With smart home:

1 |    █n indented line
2 | 

It's one of those features that you only notice when it's not there. To enable smart home by default in the config file, use:

set smarthome

Or use alt+h to turn it on and off at runtime.

Spell-Checking

The ctl+t shortcut will tell nano to check the spelling of the current open file. By default, nano attempts to invoke the spell command. If such a command is not available on your system either as a standalone program or a wrapper script, a bit of configuration is required to get the feature working. The command that nano uses to spell-check can be configured with the speller option in your config file. This takes the name of the command to run instead of spell. On my system I created a very simple wrapper script which invokes aspell with the filename given to it:

#!/bin/bash

aspell check $1

Visible Whitespace

The keyboard shortcut alt+p displays whitespace characters in the file using visible glyphs. This might be useful if you are writing a whitespace-syntax language such as Python or CoffeeScript (or, I suppose, Whitespace) and need to track down some bad indentation:

Visible whitespace off:

1 |    An indented line
2 |

Visible whitespace on:

1 |»   An·indented·line··
2 |»   ···

The feature requires some configuration before it will work. You need to define the characters used to represent tabs and spaces in your config file with the whitespace command. For example:

set whitespace "»·"

Syntax Highlighting

Nano can also highlight code syntax. Now it's a fairly basic expression-matching system, so it's not as sophisticated as a full-blown lexical analyser that a complete IDE might provide. The syntax highlighting is, admittedly, fairly ropey and can get confused easily. However, I find that it's better than no highlighting at all, and it's relatively simple to add your own highlighting rules.

The feature is enabled by including one or more of these sets of rules in the .nanorc file. It can also be turned on and off at runtime with alt+y. nano identifies the type of file by its file extension or header line, if available. Nano comes with a bunch of different sets of highlighting rules for various languages, and these are installed to /usr/share/nano. They can be activated by including them in your config file with the include command. For example:

include /usr/share/nano/pyhon.nanorc
include /usr/share/nano/ruby.nanorc
include /usr/share/nano/java.nanorc
include /usr/share/nano/nanorc.nanorc

Adding your own highlighting rules is fairly straightforward if you're familiar with regular expressions. Nano uses POSIX-flavour regular expressions (similar to egrep) to define patterns which are each rendered in their specified colour. A syntax definition starts with the syntax command followed by the definition name and file extension pattern. On subsequent lines the highlighting patterns are defined, each using the color or icolor commands, the later being a case-insensitive version. color takes the the foreground colour name, optional background colour name, and one or more patterns to match.

To illustrate, this is a short definition I created to highlight JSON data:

syntax "json" "\.json$"

# Array markers
color green "\[" "\]"

# Object markers
color cyan "\{" ":" "\}"

# Keywords
color blue "\<(true|false|null)\>"

# Numbers
color magenta "-?[0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+)?"

# Strings
color yellow "["]([^"\\]|\\.)*["]"

For more info, check out the nanorc man page.

Redefining Key Bindings

While nano's key commands are simple to learn, it's fair to say that they're pretty unusual. They will seem a little alien if you're used to more "standard" key bindings (ctl+c to copy, ctl+v to paste, ctl+s to save, etc).

So, if you like, you can redefine nano's key bindings in your config file. This is achieved with the bind command, which is followed by the key combination, function name, and the name of the menu in which this binding applies. As an example, let's rebind the save command (called writeout) to ctl+s and use ctl+o for opening files instead. These are both commands in the context of the main menu, thus we specify the menu as main.

bind ^S writeout main
bind ^O insert main

Again, see the man page for more info.

Nano as the Default Editor

Nano, like most text editors, can be used instead of vi as the default editor when editing config files with commands like vipw, vigr and visudo. This might be a good idea if you're not all that familiar with vi's key bindings, for example. You can use the following command to make nano the default editor:

export EDITOR=nano

Adding this command to /etc/profile will set it as the default for all users, or it can be added to an individual user's shell config file, such as /home/dave/.bashrc.

Conclusion

Nano is only intended to be a very basic text editor. As you've seen, however, with a touch of additional configuration it can be made that little bit more useful for editing code. I hope you have enjoyed this insight into some of nano's extra features.

]]>
Nano?

When it comes to text editors in Linux, there are two major players which have famously been causing holy wars for at least a couple of hundred years now: Vi and Emacs. They are both extremely powerful, lightweight editors whose ages are a testament to how useful they have been and continue to be.

If you are already a Vi or Emacs user, then great! If you're not, and you do a lot of code editing under Linux, you should probably consider learning one of them. So, with that in mind, here's another text editor that you may or may not have heard about: GNU Nano.

GNU Nano is a basic command-line text editor which is installed by default with many Linux distributions. Nano is not intended to be anywhere near as feature-rich as Vi or Emacs. It is a very simple tool, but this means it requires little to no time investment to start using for basic file editing tasks. Nano's core commands are easy to learn because they're written out at the bottom of the screen, and files can be navigated intuitively with the cursor keys.

I find nano extremely handy, and it has some neat features that you may not have known about. In this post, I'd like to share some of nano's more hidden capabilities.

]]>