Categories
Python

Raspberry Pi – Access to WordPress with Python wordpress-api

Would not it be nice if the Raspberry Pi could create articles on my website, modify them and become an editor?
If you use WordPress on your website, it’s relatively easy, since WordPress from version 4.8 includes the REST interface as standard and there is a corresponding plugin for older versions.

Whether the interface is available, can be easily detected by attaching ‘wp-json’ to the URL for each WordPress web page. For example, http://www.henrykoch.de/wp-json should display a Json string in the browser:

"name":"www.HenryKoch.de","description":"","url":"http:\/\/www.henrykoch.de","home":"http:\/\/www.henrykoch.de\/de","gmt_offset":2,"timezone_string":"Europe\/Berlin"

Installation python wordpress-api

For the installation of the WordPress Api for python, I am followed this guide https://pypi.python.org/pypi/wordpress-api/1.2.2, which did not work immediately.
To get the API running, additional packages had to be installed.

So I came to the result (On the Raspberry Pi)

sudo apt-get update
sudo apt-get install libxml2-dev
sudo apt-get build-dep python3-lxml
pip install wordpress-api

Libxml and lxml were missing from me.

Authentication

I spent a lot of time here.
I really wanted an OAuth authentication and I failed with the described REST oauth1 plugin.
After a long back and forth I installed this plugin: WP OAuth Server

As seen on the pictures, there is an OAuth server entry after installation on the dashboard on the left side. There I created a user. If this is done, the user is listed and a client ID is specified. Consumer_key in the phthon script
In addition, the Secret Key can now be displayed -> consumer_secret in the python script.

first test script

#!/usr/bin/python
# -*- coding: utf-8 -*-
from wordpress import api as wpapi
from wordpress import API
 
wpapi = API(
    url="http://ai.henrykoch.de/", #your URL
    consumer_key="xxxxxxxxxxxxx", #your key
    consumer_secret="xxxxxxxxxxxxx", #your secret key
    api="wp-json",
    version="wp/v2",
    wp_user="xxx",    #your wp User
    wp_pass="xxx"     #wp users password
)
r = wpapi.get("posts")
print r.status_code
print r.headers['content-type']
print r.encoding
print r.text
print r.json()

The result

pi@raspberrypi:~/python/Wordpress $ python myscript.py
200
application/json; charset=UTF-8
UTF-8
[{"id":1,"date":"2017-08-08T15:25:58","date_gmt":"2017-08-08T13:25:58","guid":{"rendered":"http:\/\/ai.henrykoch.de\/?p=1"},"modified":"2017-08-08T15:38:46","modified_gmt":"2017-08-08T13:38:46","slug":
...
Categories
Python

Raspberry Pi – Python – SQLite database – a simple frugal way to manage data professionally

The following post provides code examples in Python inclusive the complete sources for download

  1. Create a new SQLite database
  2. Create a new table
  3. Display of all tables in a database
  4. Insert values into a table
  5. View table contents
  6. Code to download

0 Preliminary two links to SQLite descriptions / tutorials

1 Create a new SQLite database

To create a database it’s enough to make a connect to a non-existing database and the database file will be created automatically.

#!/usr/bin/python
# -*- coding: utf-8 -*-
 
import sqlite3 as lite
import sys
 
def create_new_database(PfadzurDatenbank):
    try:
        con = lite.connect(PfadzurDatenbank) 
        con.commit()
 
    except lite.Error, e:
        if con:
            con.rollback()
            print "Error %s:" % e.args[0]
            sys.exit(1)
 
    finally:
        if con:
            con.close() 
 
create_new_database("/home/pi/sqlite3/BeispielDatenbank.db")
pi@raspberrypi ~/sqlite3 $ ls -al
insgesamt 580
drwxr-xr-x  2 pi pi   4096 Okt 21 10:02 .
drwxr-xr-x 12 pi pi   4096 Sep 27 20:26 ..
-rw-r--r--  1 pi pi      0 Okt 21 10:02 BeispielDatenbank.db

2 Create a new table

In the following code example, a table will be created, which will be used to store the measured values of a temperature sensor DS18820.
The table consists of three columns

  • time stamp
  • minimum temperature
  • maximum temperature

The goal for this table is to insert timestamps and temperature values. Each
row stands for a timeframe of one hour. The temperatures which are measured within the hour, will be compared to the maximum and minimum values that already stored in the table.
Bildschirmfoto vom 2015-10-21 11:14:11

If the new value is greater than the maximum value at the table, it will be replaced. If the new value is less than minimum value in the table, the minimum value will be replaced.
So regardless of the number of measurements (greater than 1) remain three values per hour (timestamp, MinTemp, MaxTemp), which is perfectly adequate for a normal measurement of space or outdoor temperatures.

#!/usr/bin/python
# -*- coding: utf-8 -*-
 
import sqlite3 as lite
import sys
 
def create_new_temperature_sensor_table(PathToDatabase, TableName):
    try:
        con = lite.connect(PathToDatabase)
        cur = con.cursor()  
        cur.executescript("""
            CREATE TABLE %s(    Timestamp INT PRIMARY KEY, 
                                Temp_MIN REAL, 
                                Temp_MAX REAL); 
            """ % TableName) 
        con.commit()
 
    except lite.Error, e:
 
        if con:
            con.rollback()
 
            print "Error %s:" % e.args[0]
            sys.exit(1)
 
    finally:
 
        if con:
            con.close() 
create_new_temperature_sensor_table("/home/pi/sqlite3/BeispielDatenbank.db", "Fuehler1")

3 Display of all tables in a database

Currently, only one table (Fuehler1) in the database was created, which can be displayed by using the following script.

#!/usr/bin/python
# -*- coding: utf-8 -*-
 
import sqlite3 as lite
import sys
def list_all_tables_in_DB(PathToDatabase):
    try:
        con = lite.connect(PathToDatabase)
 
        with con:
 
            cur = con.cursor()    
            cur.execute("SELECT name FROM sqlite_master WHERE type='table'")
 
            rows = cur.fetchall()
 
            for row in rows:
                print row[0]
 
    except lite.Error, e:
 
        if con:
            con.rollback()
 
            print "Error %s:" % e.args[0]
            sys.exit(1)
 
    finally:
 
        if con:
            con.close() 
 
list_all_tables_in_DB("/home/pi/sqlite3/BeispielDatenbank.db")
pi@raspberrypi ~/python_scripts $ python DB_Funktionen.py 
Fuehler1

4 Insert values into a table

The following is to be inserted into the table Fuehler1:

  • Timestamp: 1445432400
  • Temp_MIN: 15.0
  • Temp_MAX: 17.22
#!/usr/bin/python
# -*- coding: utf-8 -*-
 
import sqlite3 as lite
import sys
 
def insert_new_line_in_temperature_sensor_table(PathToDatabase, TableName, 
                                                Timestamp, Temp_MIN, Temp_MAX):
 
    try:
        con = lite.connect(PathToDatabase)
        cur = con.cursor()  
        cur.execute("""
            INSERT INTO %s 
            VALUES( %i , %.3f, %.3f)
            """ % (TableName, Timestamp, Temp_MIN, Temp_MAX))
        con.commit()
 
    except lite.Error, e:
 
        if con:
            con.rollback()
 
            print "Error %s:" % e.args[0]
            sys.exit(1)
 
    finally:
 
        if con:
            con.close() 
 
insert_new_line_in_temperature_sensor_table("/home/pi/sqlite3/BeispielDatenbank.db", 
                                            "Fuehler1", 1445432400, 15.0, 17.22)

5 View table contents

#!/usr/bin/python
# -*- coding: utf-8 -*-
 
import sqlite3 as lite
import sys
 
def show_all_table_entries(PathToDatabase, TableName):
    try:
        con = lite.connect(PathToDatabase)
        cur = con.cursor()  
        cur.execute("SELECT * FROM %s" % TableName)
        lines = cur.fetchall()
        for line in lines:
            print line
        con.commit()
 
    except lite.Error, e:
        if con:
            con.rollback()
            print "Error %s:" % e.args[0]
            sys.exit(1)
 
    finally:
        if con:
            con.close()
show_all_table_entries("/home/pi/sqlite3/BeispielDatenbank.db", "Fuehler1")
pi@raspberrypi ~/python_scripts $ python DB_Funktionen.py 
(1445432400, 15.0, 17.22)

6 Code to download

download: DB_Funktionen.py

Categories
Python

(Deutsch) Raspberry Pi – Python – (HC-SR04) Ultraschall Abstandsmessung – fehlerhafte Ergebnisse durch Statistik in den Griff bekommen – Teil1

Sorry, this entry is only available in German.

Categories
Python

Python – remove oldest files in a directory, only a defined count of them remains

By experimenting with the Pi camera and PIR at may Raspberry Pi were quickly many images written to the SD card.

In order to get some control, the following Python Script is a good basis.
There is the possibility to specify a directory and the maximum number of files stored in it.

Exceeds the number of files the defined value, older files are deleted.

In my case, I always keep a maximum of 1000 images in the folder.

Sample code:

#!/usr/bin/python
 
import os
 
path = "/home/pi/pictures/"
max_Files = 1000
 
def sorted_ls(path):
    mtime = lambda f: os.stat(os.path.join(path, f)).st_mtime
    return list(sorted(os.listdir(path), key=mtime))
 
del_list = sorted_ls(path)[0:(len(sorted_ls(path))-max_Files)]
 
for dfile in del_list:
    os.remove(path + dfile)