SlideShare ist ein Scribd-Unternehmen logo
1 von 39
Downloaden Sie, um offline zu lesen
PL/Python	
  
PostgreSQL	
  +	
  PostGIS	
  
phil.bar6e@s6r.ac.uk	
  
Crea6ng	
  Func6ons	
  in	
  PostgreSQL	
  
Other	
  than	
  SQL	
  and	
  C	
  PostgreSQL	
  allows	
  func6ons	
  to	
  
be	
  wriBen	
  in:	
  
	
  
•  PL/pgSQL	
  –	
  SQL	
  procedural	
  language	
  
•  PL/Tcl	
  –	
  Tcl	
  Procedural	
  language	
  
•  PL/Perl	
  –	
  Perl	
  Procedural	
  language	
  
•  PL/Python	
  –	
  Python	
  procedural	
  language	
  
	
  	
  	
  	
  	
  	
  +	
  addi&onal	
  	
  (eg	
  R,	
  Ruby,	
  Java,	
  PHP,	
  Unix	
  shell)	
  
h+p://www.postgresql.org/docs/9.3/sta&c/xplang.html	
  
standard	
  
Workflow	
  
•  Set	
  up	
  PC	
  	
  
–  PostgreSQL	
  install	
  
–  Corresponding	
  Python	
  install	
  
	
  
•  Set	
  up	
  DB	
  	
  
–  Create	
  database	
  
–  Add	
  the	
  PL/Python	
  extension	
  (create	
  extension)	
  
•  Create	
  Func6on	
  
•  Use	
  Func6on	
  
PL/Python	
  
•  plpython2u	
  
•  plpython3u	
  
Windows	
  	
  
	
  
PostgreSQL	
  9.3	
  is	
  compiled	
  against	
  Python	
  3.2	
  
	
  
PostgreSQL	
  9.4	
  is	
  compiled	
  against	
  Python	
  3.3	
  
	
  
pg	
  428	
  
untrusted	
  language	
  =	
  	
  can	
  access	
  file	
  system	
  of	
  OS	
  
•  Check	
  matching	
  versions	
  of	
  PostgreSQL	
  distribu&on	
  
and	
  Python	
  (inc	
  32bit	
  vs	
  64	
  bit)	
  
•  Install	
  modules	
  for	
  correct	
  Python	
  version	
  
Installa6on	
  on	
  Ubuntu	
  
Add	
  plpython	
  to	
  exsi6ng	
  PostgreSQL	
  install	
  
	
  
	
  
	
  	
  	
  	
  	
  sudo apt-get install postgresql-plpython-9.3
Adding	
  extension	
  to	
  a	
  DB	
  
Create	
  DB
CREATE DATABASE test WITH OWNER = postgres ;	
  	
  	
  	
  
	
  
	
  
Add	
  PostGIS	
  
CREATE EXTENSION postgis;
	
  
Add	
  Python	
  
CREATE EXTENSION plpython3u;
	
  
	
  
Adding	
  Python	
  Modules	
  (op6onal)	
  
Install	
  PIP	
  	
  	
  (search	
  Google	
  for	
  getpip.py)	
  
Then	
  use	
  pip	
  to	
  install	
  modules….	
  
	
  
pip install [module]
	
  
	
  
	
  
Windows	
  	
  
(if	
  need	
  to	
  add	
  pip	
  for	
  Python	
  3.x	
  when	
  already	
  have	
  Python	
  2.x	
  on	
  PC)	
  
	
  
hBps://sites.google.com/site/pydatalog/python/pip-­‐for-­‐windows	
  	
  	
  
(updated	
  March	
  2015)	
  
	
  
(run	
  as	
  administrator)	
  
Simple	
  Example	
  
•  Create	
  Func6on	
  to	
  Use	
  Python	
  to	
  Return	
  MAX	
  of	
  
Two	
  Values	
  
CREATE FUNCTION pymax (a integer, b integer)
RETURNS integer
AS $$
if a  b:
return a
return b
$$ LANGUAGE plpython3u;
Trying	
  it	
  Out	
  
SELECT * FROM pymax (10,29);
29
SELECT * FROM pymax (5012,-42);
5012
	
  
Overloading	
  
CREATE FUNCTION pymax (a integer, b integer, c
integer)
RETURNS integer
AS $$
m=a
if (b  m): m=b
if (c  m): m=c
return m
$$ LANGUAGE plpython3u;
Tests	
  
SELECT * FROM pymax (1,2,3); -- 3
SELECT * FROM pymax (3,2,1); -- 3
SELECT * FROM pymax (1,3,2); -- 3
 Quicker	
  Way	
  
CREATE FUNCTION pymax (a integer, b integer,
c integer, d integer)
RETURNS integer
AS $$
return max (a,b,c,d)
$$ LANGUAGE plpython3u;
Tests	
  
SELECT * FROM pymax (1,2,3,4); -- 4
SELECT * FROM pymax (4,3,2,1); -- 4
SELECT * FROM pymax (1,4,3,2); -- 4
SELECT * FROM pymax (1,3,4,2); -- 4
Other	
  Data	
  Types	
  
CREATE OR REPLACE FUNCTION py_reverse (t text)
RETURNS text AS
$$
return t[::-1]
$$
LANGUAGE plpython3u;
SELECT py_reverse ('spam, spam, spam');
maps, maps ,maps
Custom	
  Data	
  Types	
  
CREATE TYPE basic_stats AS
(
avg double precision,
stddev double precision,
max double precision,
min double precision
);
Returning	
  Custom	
  Type	
  
CREATE OR REPLACE FUNCTION py_stats (a integer,
b integer, c integer)
RETURNS SETOF basic_stats
AS $$
import numpy as np
l = [a,b,c]
result=[]
item=[]
item.append(np.mean(l)) #mean
item.append(np.std(l)) #standard deviation
item.append(np.max(l)) #max
item.append(np.min(l)) #min
result.append(item)return result
$$
LANGUAGE plpython3u;
Example	
  
SELECT * FROM py_stats(10,23,25);
Return	
  a	
  Table	
  
CREATE TABLE client
(
client_id serial,
primary_address text,
street text,
postcode text
)
INSERT INTO client (primary_address,street,postcode) values
('12/82','first street','ZZ156B');
INSERT INTO client (primary_address,street,postcode) values
('9/82','thrid street','ZZ252S');
INSERT INTO client (primary_address,street,postcode) values
('2/8','first street','ZZ226D');
CREATE OR REPLACE FUNCTION py_clientdemo (cid
integer)
RETURNS SETOF client
AS $$
rv = plpy.execute(SELECT * FROM client where
client_id  +str(cid) + ';' )
return rv
$$
LANGUAGE plpython3u;
SELECT	
  *	
  FROM	
  py_clientdemo(3);	
  
Lots	
  of	
  FuncGons…	
  
To	
  find	
  your	
  func6ons	
  more	
  easily..	
  
	
  
	
  
a)  Could	
  prefix	
  them	
  all	
  (eg	
  py_)	
  
b)  Could	
  put	
  them	
  in	
  a	
  separate	
  schema	
  
Using	
  Schemas	
  
CREATE SCHEMA fn;
ALTER FUNCTION pymax (integer,integer) SET SCHEMA fn;
ALTER FUNCTION pymax (integer,integer,integer) SET SCHEMA fn;
ALTER FUNCTION pymax (integer,integer,integer,integer) SET SCHEMA fn;
SELECT pymax (1,20);
ERROR: function pymax(integer, integer) does not exist
LINE 1: SELECT pymax (1,20);
^HINT: No function matches the given name and argument types. You
might need to add explicit type casts.********** Error **********
SELECT fn.pymax (1,20);
20
Read	
  from	
  an	
  XL	
  spreadsheet	
  
DROP	
  FUNCTION	
  py_readxl(text);	
  
	
  
CREATE	
  OR	
  REPLACE	
  FUNCTION	
  py_readxl	
  (fn	
  text,	
  OUT	
  x	
  float,	
  OUT	
  y	
  float)	
  
RETURNS	
  SETOF	
  RECORD	
  AS	
  
$$	
  
import	
  xlrd	
  
book=xlrd.open_workbook	
  (fn)	
  
sh=book.sheet_by_index(0)	
  
for	
  rx	
  in	
  range	
  (1,sh.nrows):	
  
	
  	
  	
  	
  yield(	
  
	
  	
  	
  	
  	
  	
  	
  	
  sh.cell_value(rowx=rx,colx=0),	
  
	
  	
  	
  	
  	
  	
  	
  	
  sh.cell_value(rowx=rx,colx=1)	
  
	
  	
  	
  	
  	
  	
  	
  	
  )	
  
$$	
  
LANGUAGE	
  'plpython3u'	
  VOLATILE	
  
	
  
	
  
SELECT	
  x,y,st_makepoint(x,y)	
  FROM	
  py_readxl('c:/data/python/points.xlsx');	
  
Export	
  PNG	
  file	
  
	
  
CREATE	
  OR	
  REPLACE	
  FUNCTION	
  py_exportpng(bytes	
  bytea,	
  fn	
  text)	
  
	
  	
  RETURNS	
  text	
  AS	
  
$$	
  
f=open('c:/data/python/'+fn,'wb+')
f.write(bytes)
f.close()
return fn	
  
$$	
  
	
  	
  LANGUAGE	
  plpython3u	
  IMMUTABLE	
  
	
  	
  COST	
  100;	
  
SELECT py_exportpng(ST_AsPNG(ST_AsRaster(ST_Collect((ST_Buffer(geom,
10))),400,400)),'roads.png')
FROM roads;
Geocode	
  Example	
  
CREATE OR REPLACE FUNCTION py_geocode(t text, OUT address
text, OUT lat numeric, OUT lng numeric)
RETURNS record AS
$BODY$
FROM geopy import geocoders
g=geocoders.GoogleV3()
address,(lat,lng)=g.geocode (t,timeout=20)
return address,lat, lng
$BODY$
LANGUAGE plpython3u
Example	
  
SELECT	
  *,	
  st_makepoint(lng,lat)	
  as	
  pt	
  
FROM	
  py_geocode	
  ('Princes	
  Street,	
  Edinburgh');	
  
Python	
  TCP	
  
#	
  SERVER	
  SIDE	
  
import	
  socket	
  
HOST	
  =	
  ''	
  #	
  meaning	
  the	
  local	
  host	
  
PORT	
  =	
  8889	
  #	
  Arbitrary	
  port	
  
s	
  =	
  socket.socket(socket.AF_INET,socket.SOCK_STREAM)	
  
s.bind((HOST,	
  PORT))	
  
s.listen(1)	
  
	
  
print	
  ('wai6ng	
  of	
  the	
  client	
  to	
  connect')	
  
conn,	
  addr	
  =	
  s.accept()	
  
	
  
print	
  ('Connected	
  by',	
  addr)	
  
data	
  =	
  conn.recv(1024)	
  
print	
  (data)	
  
	
  
conn.send(data)	
  
conn.close()	
  
s.close()	
  
PC1	
  
PC2	
  
Check	
  firewall	
  
(TCP	
  port	
  open)	
  
CREATE	
  OR	
  REPLACE	
  FUNCTION	
  pytcp(x	
  integer,	
  y	
  integer)	
  
	
  	
  RETURNS	
  text	
  AS	
  
$BODY$	
  
	
  
import	
  socket	
  
HOST	
  =	
  '127.0.0.1'	
  
#desktop's	
  IP	
  
PORT	
  =	
  8889	
  
s	
  =	
  socket.socket(socket.AF_INET,socket.SOCK_STREAM)	
  
s.connect((HOST,	
  PORT))	
  	
  
s.send((str(x)	
  +	
  str(y)).encode('ur-­‐8'))	
  
data	
  =	
  s.recv(1024).decode('ur-­‐8')	
  
s.close()	
  
return	
  data	
  
	
  
$BODY$	
  
	
  	
  LANGUAGE	
  plpython3u	
  VOLATILE	
  
	
  	
  COST	
  100;	
  
ALTER	
  FUNCTION	
  pytcp(integer,	
  integer)	
  
	
  	
  OWNER	
  TO	
  postgres;	
  
NERC	
  ViPER	
  
C#	
  Server	
  
Queue	
  
PL/Python	
  	
  
(TCP)	
  
D3	
  /	
  Leaflet	
  JS	
   DB	
  Insert	
  
PHP	
  
MatLab	
  
Run6me	
  
Python	
  Send	
  Email	
  
CREATE OR REPLACE FUNCTION
sendemail(r text, s text, m text)
RETURNS void AS
$BODY$
import smtplib
import time
session = smtplib.SMTP('smtp.gmail.com',
587)
session.ehlo()
session.starttls()
GMAIL_USERNAME =
'your_send_email_address@gmail.com’
GMAIL_PASSWORD = '**********’
recipient = str(r)
email_subject= str(s)
body_of_email = str(m)
session.login(GMAIL_USERNAME,
GMAIL_PASSWORD)
headers = rn.join([FROM:  +
'noreply@noreply.com',
subject:  +
email_subject,
to:  + recipient,
mime-version: 1.0,
content-type: text/
html])
# body_of_email can be plaintext or html!
content = headers + rnrn + body_of_email
session.sendmail(GMAIL_USERNAME, recipient,
content)
session.quit()
time.sleep(2)
return ;
$BODY$
LANGUAGE plpython3u VOLATILE
COST 250;
ALTER FUNCTION sendemail(text, text, text)
OWNER TO postgres;
Google	
  GMail	
  Sesngs	
  
Send	
  an	
  email	
  or	
  two	
  using	
  their	
  web	
  based	
  UI	
  
first..	
  otherwise	
  they	
  may	
  block	
  the	
  account.	
  
Example	
  Message	
  
SELECT
sendemail (emailaddress,’New Local Offer','Hi '||
firstname||',
Just letting you know we will be offering locals in
the '|| region || ‘discounts of up to 10% from 5th
May for 2 weeks by using this voucher code …blah
blah blah’)
FROM clients
WHERE st_dwithin
(geom,st_setsrid(st_makepoint('324356','672910'),
27700),1000)
ORDER BY clientid desc;
Raspberry	
  PI	
  2	
  
PI2	
  running…	
  
hBps://www.raspberrypi.org/forums/viewtopic.php?t=98997	
  
	
  	
  
Using	
  it	
  for	
  PostgreSQL	
  +	
  PostGIS	
  +	
  Python	
  +	
  Apache2	
  +	
  Leaflet	
  
Ubuntu	
  14.10	
  /	
  Linaro	
  15.01	
  	
  
(University	
  of	
  S6rling)	
  
phil.bar6e@s6r.ac.uk	
  

Weitere ähnliche Inhalte

Was ist angesagt?

"A 1,500 line (!!) switch statement powers your Python!" - Allison Kaptur, !!...
"A 1,500 line (!!) switch statement powers your Python!" - Allison Kaptur, !!..."A 1,500 line (!!) switch statement powers your Python!" - Allison Kaptur, !!...
"A 1,500 line (!!) switch statement powers your Python!" - Allison Kaptur, !!...
akaptur
 
Functional programming in Python
Functional programming in PythonFunctional programming in Python
Functional programming in Python
Colin Su
 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2go
Moriyoshi Koizumi
 
A peek on numerical programming in perl and python e christopher dyken 2005
A peek on numerical programming in perl and python  e christopher dyken  2005A peek on numerical programming in perl and python  e christopher dyken  2005
A peek on numerical programming in perl and python e christopher dyken 2005
Jules Krdenas
 

Was ist angesagt? (20)

C Programming Homework Help
C Programming Homework HelpC Programming Homework Help
C Programming Homework Help
 
Functional Programming inside OOP? It’s possible with Python
Functional Programming inside OOP? It’s possible with PythonFunctional Programming inside OOP? It’s possible with Python
Functional Programming inside OOP? It’s possible with Python
 
Exploring slides
Exploring slidesExploring slides
Exploring slides
 
Flux and InfluxDB 2.0
Flux and InfluxDB 2.0Flux and InfluxDB 2.0
Flux and InfluxDB 2.0
 
Docopt
DocoptDocopt
Docopt
 
Implementing Software Machines in C and Go
Implementing Software Machines in C and GoImplementing Software Machines in C and Go
Implementing Software Machines in C and Go
 
Stack
StackStack
Stack
 
"A 1,500 line (!!) switch statement powers your Python!" - Allison Kaptur, !!...
"A 1,500 line (!!) switch statement powers your Python!" - Allison Kaptur, !!..."A 1,500 line (!!) switch statement powers your Python!" - Allison Kaptur, !!...
"A 1,500 line (!!) switch statement powers your Python!" - Allison Kaptur, !!...
 
Functional programming in Python
Functional programming in PythonFunctional programming in Python
Functional programming in Python
 
Jan 2012 HUG: RHadoop
Jan 2012 HUG: RHadoopJan 2012 HUG: RHadoop
Jan 2012 HUG: RHadoop
 
Implementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 reduxImplementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 redux
 
Are we ready to Go?
Are we ready to Go?Are we ready to Go?
Are we ready to Go?
 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2go
 
Chapter2 Haskell
Chapter2 HaskellChapter2 Haskell
Chapter2 Haskell
 
C Assignment Help
C Assignment HelpC Assignment Help
C Assignment Help
 
The secrets of inverse brogramming
The secrets of inverse brogrammingThe secrets of inverse brogramming
The secrets of inverse brogramming
 
Python 培训讲义
Python 培训讲义Python 培训讲义
Python 培训讲义
 
Generic Functional Programming with Type Classes
Generic Functional Programming with Type ClassesGeneric Functional Programming with Type Classes
Generic Functional Programming with Type Classes
 
Go a crash course
Go   a crash courseGo   a crash course
Go a crash course
 
A peek on numerical programming in perl and python e christopher dyken 2005
A peek on numerical programming in perl and python  e christopher dyken  2005A peek on numerical programming in perl and python  e christopher dyken  2005
A peek on numerical programming in perl and python e christopher dyken 2005
 

Ähnlich wie Phil Bartie QGIS PLPython

Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
Sigma Software
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
Dmitry Buzdin
 

Ähnlich wie Phil Bartie QGIS PLPython (20)

Pl python python w postgre-sql
Pl python   python w postgre-sqlPl python   python w postgre-sql
Pl python python w postgre-sql
 
What's new in Python 3.11
What's new in Python 3.11What's new in Python 3.11
What's new in Python 3.11
 
Implementing Software Machines in Go and C
Implementing Software Machines in Go and CImplementing Software Machines in Go and C
Implementing Software Machines in Go and C
 
Imugi: Compiler made with Python
Imugi: Compiler made with PythonImugi: Compiler made with Python
Imugi: Compiler made with Python
 
Cpp tutorial
Cpp tutorialCpp tutorial
Cpp tutorial
 
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
 
Psycopg2 - Connect to PostgreSQL using Python Script
Psycopg2 - Connect to PostgreSQL using Python ScriptPsycopg2 - Connect to PostgreSQL using Python Script
Psycopg2 - Connect to PostgreSQL using Python Script
 
4.1-Pig.pptx
4.1-Pig.pptx4.1-Pig.pptx
4.1-Pig.pptx
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
 
Java VS Python
Java VS PythonJava VS Python
Java VS Python
 
CppTutorial.ppt
CppTutorial.pptCppTutorial.ppt
CppTutorial.ppt
 
"PostgreSQL and Python" Lightning Talk @EuroPython2014
"PostgreSQL and Python" Lightning Talk @EuroPython2014"PostgreSQL and Python" Lightning Talk @EuroPython2014
"PostgreSQL and Python" Lightning Talk @EuroPython2014
 
C++ manual Report Full
C++ manual Report FullC++ manual Report Full
C++ manual Report Full
 
Python 3000
Python 3000Python 3000
Python 3000
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Use of django at jolt online v3
Use of django at jolt online v3Use of django at jolt online v3
Use of django at jolt online v3
 
Compiler Construction | Lecture 12 | Virtual Machines
Compiler Construction | Lecture 12 | Virtual MachinesCompiler Construction | Lecture 12 | Virtual Machines
Compiler Construction | Lecture 12 | Virtual Machines
 
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
 
Python 3000
Python 3000Python 3000
Python 3000
 

Mehr von Ross McDonald

Mehr von Ross McDonald (20)

Visualising school catchment areas - FOSS4GUK 2018
Visualising school catchment areas - FOSS4GUK 2018Visualising school catchment areas - FOSS4GUK 2018
Visualising school catchment areas - FOSS4GUK 2018
 
Using QGIS to create 3D indoor maps
Using QGIS to create 3D indoor mapsUsing QGIS to create 3D indoor maps
Using QGIS to create 3D indoor maps
 
Creating and indoor routable network with QGIS and pgRouting
Creating and indoor routable network with QGIS and pgRoutingCreating and indoor routable network with QGIS and pgRouting
Creating and indoor routable network with QGIS and pgRouting
 
Viewsheds and Advanced Calculations
Viewsheds and Advanced CalculationsViewsheds and Advanced Calculations
Viewsheds and Advanced Calculations
 
Using QGIS for ecological surveying
Using QGIS for ecological surveyingUsing QGIS for ecological surveying
Using QGIS for ecological surveying
 
Welcome to the 6th Scottish QGIS UK meeting
Welcome to the 6th Scottish QGIS UK meetingWelcome to the 6th Scottish QGIS UK meeting
Welcome to the 6th Scottish QGIS UK meeting
 
How deep is your loch?
How deep is your loch?How deep is your loch?
How deep is your loch?
 
Data capture with Leaflet and OpenStreetMap
Data capture with Leaflet and OpenStreetMapData capture with Leaflet and OpenStreetMap
Data capture with Leaflet and OpenStreetMap
 
Them thar hills: shadin', texturin', blendin'
Them thar hills: shadin', texturin', blendin'Them thar hills: shadin', texturin', blendin'
Them thar hills: shadin', texturin', blendin'
 
QGIS plugin for parallel processing in terrain analysis
QGIS plugin for parallel processing in terrain analysisQGIS plugin for parallel processing in terrain analysis
QGIS plugin for parallel processing in terrain analysis
 
Mapping narrative: QGIS in the humanities classrom
Mapping narrative: QGIS in the humanities classromMapping narrative: QGIS in the humanities classrom
Mapping narrative: QGIS in the humanities classrom
 
QGIS server: the good, the not-so-good and the ugly
QGIS server: the good, the not-so-good and the uglyQGIS server: the good, the not-so-good and the ugly
QGIS server: the good, the not-so-good and the ugly
 
QGIS UK Thank you for coming
QGIS UK Thank you for comingQGIS UK Thank you for coming
QGIS UK Thank you for coming
 
Decision support tools for forestry using open source software
Decision support tools for forestry using open source softwareDecision support tools for forestry using open source software
Decision support tools for forestry using open source software
 
Installing QGIS on a network
Installing QGIS on a networkInstalling QGIS on a network
Installing QGIS on a network
 
Pgrouting_foss4guk_ross_mcdonald
Pgrouting_foss4guk_ross_mcdonaldPgrouting_foss4guk_ross_mcdonald
Pgrouting_foss4guk_ross_mcdonald
 
Liam Mason QGIS Geoserver SLD
Liam Mason QGIS Geoserver SLDLiam Mason QGIS Geoserver SLD
Liam Mason QGIS Geoserver SLD
 
John Stevenson Volcanoes and FOSS4G Edinburgh
John Stevenson Volcanoes and FOSS4G EdinburghJohn Stevenson Volcanoes and FOSS4G Edinburgh
John Stevenson Volcanoes and FOSS4G Edinburgh
 
Roger Garbett - QGIS Print Composer
Roger Garbett - QGIS Print ComposerRoger Garbett - QGIS Print Composer
Roger Garbett - QGIS Print Composer
 
Matt Walsh thinkWhere_QGIS_usergroup_pyqt
Matt Walsh thinkWhere_QGIS_usergroup_pyqtMatt Walsh thinkWhere_QGIS_usergroup_pyqt
Matt Walsh thinkWhere_QGIS_usergroup_pyqt
 

Kürzlich hochgeladen

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Kürzlich hochgeladen (20)

FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 

Phil Bartie QGIS PLPython

  • 1. PL/Python   PostgreSQL  +  PostGIS   phil.bar6e@s6r.ac.uk  
  • 2. Crea6ng  Func6ons  in  PostgreSQL   Other  than  SQL  and  C  PostgreSQL  allows  func6ons  to   be  wriBen  in:     •  PL/pgSQL  –  SQL  procedural  language   •  PL/Tcl  –  Tcl  Procedural  language   •  PL/Perl  –  Perl  Procedural  language   •  PL/Python  –  Python  procedural  language              +  addi&onal    (eg  R,  Ruby,  Java,  PHP,  Unix  shell)   h+p://www.postgresql.org/docs/9.3/sta&c/xplang.html   standard  
  • 3. Workflow   •  Set  up  PC     –  PostgreSQL  install   –  Corresponding  Python  install     •  Set  up  DB     –  Create  database   –  Add  the  PL/Python  extension  (create  extension)   •  Create  Func6on   •  Use  Func6on  
  • 4. PL/Python   •  plpython2u   •  plpython3u   Windows       PostgreSQL  9.3  is  compiled  against  Python  3.2     PostgreSQL  9.4  is  compiled  against  Python  3.3     pg  428   untrusted  language  =    can  access  file  system  of  OS   •  Check  matching  versions  of  PostgreSQL  distribu&on   and  Python  (inc  32bit  vs  64  bit)   •  Install  modules  for  correct  Python  version  
  • 5. Installa6on  on  Ubuntu   Add  plpython  to  exsi6ng  PostgreSQL  install                sudo apt-get install postgresql-plpython-9.3
  • 6. Adding  extension  to  a  DB   Create  DB CREATE DATABASE test WITH OWNER = postgres ;             Add  PostGIS   CREATE EXTENSION postgis;   Add  Python   CREATE EXTENSION plpython3u;    
  • 7. Adding  Python  Modules  (op6onal)   Install  PIP      (search  Google  for  getpip.py)   Then  use  pip  to  install  modules….     pip install [module]       Windows     (if  need  to  add  pip  for  Python  3.x  when  already  have  Python  2.x  on  PC)     hBps://sites.google.com/site/pydatalog/python/pip-­‐for-­‐windows       (updated  March  2015)     (run  as  administrator)  
  • 8. Simple  Example   •  Create  Func6on  to  Use  Python  to  Return  MAX  of   Two  Values   CREATE FUNCTION pymax (a integer, b integer) RETURNS integer AS $$ if a b: return a return b $$ LANGUAGE plpython3u;
  • 9. Trying  it  Out   SELECT * FROM pymax (10,29); 29 SELECT * FROM pymax (5012,-42); 5012  
  • 10. Overloading   CREATE FUNCTION pymax (a integer, b integer, c integer) RETURNS integer AS $$ m=a if (b m): m=b if (c m): m=c return m $$ LANGUAGE plpython3u;
  • 11. Tests   SELECT * FROM pymax (1,2,3); -- 3 SELECT * FROM pymax (3,2,1); -- 3 SELECT * FROM pymax (1,3,2); -- 3
  • 12.  Quicker  Way   CREATE FUNCTION pymax (a integer, b integer, c integer, d integer) RETURNS integer AS $$ return max (a,b,c,d) $$ LANGUAGE plpython3u;
  • 13. Tests   SELECT * FROM pymax (1,2,3,4); -- 4 SELECT * FROM pymax (4,3,2,1); -- 4 SELECT * FROM pymax (1,4,3,2); -- 4 SELECT * FROM pymax (1,3,4,2); -- 4
  • 14. Other  Data  Types   CREATE OR REPLACE FUNCTION py_reverse (t text) RETURNS text AS $$ return t[::-1] $$ LANGUAGE plpython3u; SELECT py_reverse ('spam, spam, spam'); maps, maps ,maps
  • 15. Custom  Data  Types   CREATE TYPE basic_stats AS ( avg double precision, stddev double precision, max double precision, min double precision );
  • 16. Returning  Custom  Type   CREATE OR REPLACE FUNCTION py_stats (a integer, b integer, c integer) RETURNS SETOF basic_stats AS $$ import numpy as np l = [a,b,c] result=[] item=[] item.append(np.mean(l)) #mean item.append(np.std(l)) #standard deviation item.append(np.max(l)) #max item.append(np.min(l)) #min result.append(item)return result $$ LANGUAGE plpython3u;
  • 17. Example   SELECT * FROM py_stats(10,23,25);
  • 18. Return  a  Table   CREATE TABLE client ( client_id serial, primary_address text, street text, postcode text ) INSERT INTO client (primary_address,street,postcode) values ('12/82','first street','ZZ156B'); INSERT INTO client (primary_address,street,postcode) values ('9/82','thrid street','ZZ252S'); INSERT INTO client (primary_address,street,postcode) values ('2/8','first street','ZZ226D');
  • 19. CREATE OR REPLACE FUNCTION py_clientdemo (cid integer) RETURNS SETOF client AS $$ rv = plpy.execute(SELECT * FROM client where client_id +str(cid) + ';' ) return rv $$ LANGUAGE plpython3u;
  • 20. SELECT  *  FROM  py_clientdemo(3);  
  • 21. Lots  of  FuncGons…   To  find  your  func6ons  more  easily..       a)  Could  prefix  them  all  (eg  py_)   b)  Could  put  them  in  a  separate  schema  
  • 22. Using  Schemas   CREATE SCHEMA fn; ALTER FUNCTION pymax (integer,integer) SET SCHEMA fn; ALTER FUNCTION pymax (integer,integer,integer) SET SCHEMA fn; ALTER FUNCTION pymax (integer,integer,integer,integer) SET SCHEMA fn; SELECT pymax (1,20); ERROR: function pymax(integer, integer) does not exist LINE 1: SELECT pymax (1,20); ^HINT: No function matches the given name and argument types. You might need to add explicit type casts.********** Error ********** SELECT fn.pymax (1,20); 20
  • 23.
  • 24. Read  from  an  XL  spreadsheet   DROP  FUNCTION  py_readxl(text);     CREATE  OR  REPLACE  FUNCTION  py_readxl  (fn  text,  OUT  x  float,  OUT  y  float)   RETURNS  SETOF  RECORD  AS   $$   import  xlrd   book=xlrd.open_workbook  (fn)   sh=book.sheet_by_index(0)   for  rx  in  range  (1,sh.nrows):          yield(                  sh.cell_value(rowx=rx,colx=0),                  sh.cell_value(rowx=rx,colx=1)                  )   $$   LANGUAGE  'plpython3u'  VOLATILE       SELECT  x,y,st_makepoint(x,y)  FROM  py_readxl('c:/data/python/points.xlsx');  
  • 25. Export  PNG  file     CREATE  OR  REPLACE  FUNCTION  py_exportpng(bytes  bytea,  fn  text)      RETURNS  text  AS   $$   f=open('c:/data/python/'+fn,'wb+') f.write(bytes) f.close() return fn   $$      LANGUAGE  plpython3u  IMMUTABLE      COST  100;  
  • 27. Geocode  Example   CREATE OR REPLACE FUNCTION py_geocode(t text, OUT address text, OUT lat numeric, OUT lng numeric) RETURNS record AS $BODY$ FROM geopy import geocoders g=geocoders.GoogleV3() address,(lat,lng)=g.geocode (t,timeout=20) return address,lat, lng $BODY$ LANGUAGE plpython3u
  • 28. Example   SELECT  *,  st_makepoint(lng,lat)  as  pt   FROM  py_geocode  ('Princes  Street,  Edinburgh');  
  • 29. Python  TCP   #  SERVER  SIDE   import  socket   HOST  =  ''  #  meaning  the  local  host   PORT  =  8889  #  Arbitrary  port   s  =  socket.socket(socket.AF_INET,socket.SOCK_STREAM)   s.bind((HOST,  PORT))   s.listen(1)     print  ('wai6ng  of  the  client  to  connect')   conn,  addr  =  s.accept()     print  ('Connected  by',  addr)   data  =  conn.recv(1024)   print  (data)     conn.send(data)   conn.close()   s.close()   PC1   PC2   Check  firewall   (TCP  port  open)  
  • 30. CREATE  OR  REPLACE  FUNCTION  pytcp(x  integer,  y  integer)      RETURNS  text  AS   $BODY$     import  socket   HOST  =  '127.0.0.1'   #desktop's  IP   PORT  =  8889   s  =  socket.socket(socket.AF_INET,socket.SOCK_STREAM)   s.connect((HOST,  PORT))     s.send((str(x)  +  str(y)).encode('ur-­‐8'))   data  =  s.recv(1024).decode('ur-­‐8')   s.close()   return  data     $BODY$      LANGUAGE  plpython3u  VOLATILE      COST  100;   ALTER  FUNCTION  pytcp(integer,  integer)      OWNER  TO  postgres;  
  • 31. NERC  ViPER   C#  Server   Queue   PL/Python     (TCP)   D3  /  Leaflet  JS   DB  Insert   PHP   MatLab   Run6me  
  • 32.
  • 33.
  • 34. Python  Send  Email   CREATE OR REPLACE FUNCTION sendemail(r text, s text, m text) RETURNS void AS $BODY$ import smtplib import time session = smtplib.SMTP('smtp.gmail.com', 587) session.ehlo() session.starttls() GMAIL_USERNAME = 'your_send_email_address@gmail.com’ GMAIL_PASSWORD = '**********’ recipient = str(r) email_subject= str(s) body_of_email = str(m) session.login(GMAIL_USERNAME, GMAIL_PASSWORD) headers = rn.join([FROM: + 'noreply@noreply.com', subject: + email_subject, to: + recipient, mime-version: 1.0, content-type: text/ html]) # body_of_email can be plaintext or html! content = headers + rnrn + body_of_email session.sendmail(GMAIL_USERNAME, recipient, content) session.quit() time.sleep(2) return ; $BODY$ LANGUAGE plpython3u VOLATILE COST 250; ALTER FUNCTION sendemail(text, text, text) OWNER TO postgres;
  • 35. Google  GMail  Sesngs   Send  an  email  or  two  using  their  web  based  UI   first..  otherwise  they  may  block  the  account.  
  • 36. Example  Message   SELECT sendemail (emailaddress,’New Local Offer','Hi '|| firstname||', Just letting you know we will be offering locals in the '|| region || ‘discounts of up to 10% from 5th May for 2 weeks by using this voucher code …blah blah blah’) FROM clients WHERE st_dwithin (geom,st_setsrid(st_makepoint('324356','672910'), 27700),1000) ORDER BY clientid desc;
  • 38. PI2  running…   hBps://www.raspberrypi.org/forums/viewtopic.php?t=98997       Using  it  for  PostgreSQL  +  PostGIS  +  Python  +  Apache2  +  Leaflet   Ubuntu  14.10  /  Linaro  15.01    
  • 39. (University  of  S6rling)   phil.bar6e@s6r.ac.uk