Skip to content
Snippets Groups Projects
Verified Commit ce3c2ddc authored by David Beniamine's avatar David Beniamine
Browse files

Fix syntax errors

parent 74d5053f
Branches
No related tags found
No related merge requests found
%% Cell type:markdown id: tags:
## Affichage des données
%% Cell type:code id: tags:
``` python
import pymonetdb
from bokeh.plotting import figure, output_file, show
from bokeh.models import ColumnDataSource
import pandas as pd
import numpy as np
import panel as pn
from os import environ
pn.extension(comms='ipywidgets')
```
%% Output
%% Cell type:code id: tags:
``` python
def create_connection():
return pymonetdb.connect(username="monetdb", password="monetdb",
hostname="localDB", database="db")
return pymonetdb.connect(username=environ.get('LOCALDB_USER'), password=environ.get('LOCALDB_PASSWORD'),
hostname=environ.get('LOCALDB_HOST'), database="db")
def checkTableExists(dbcon, tablename):
dbcur = dbcon.cursor()
dbcur.execute("""
SELECT COUNT(*)
FROM tables
WHERE name = '{0}'
""".format(tablename.replace('\'', '\'\'')))
if dbcur.fetchone()[0] == 1:
dbcur.close()
return True
dbcur.close()
return False
def get_sql_script_content(filename):
sql_script_file = open(filename, "r")
sql_script_content = sql_script_file.read()
sql_script_file.close()
return sql_script_content
def execute_file_script(dbcon, filename):
sql_script_content = get_sql_script_content(filename)
execute_moneydb_script(connection, sql_script_content)
dbcon.command(sqlscript)
connection.commit()
dbcon.command(sql_script_content)
dbcon.commit()
def create_database():
def create_database(connection):
execute_file_script(connection, "naissances.sql")
condb = create_connection()
if checkTableExists(condb, "naissances") == False:
create_database(condb)
condb.close()
```
%% Output
---------------------------------------------------------------------------
KeyboardInterrupt Traceback (most recent call last)
<ipython-input-17-4e8172277b2f> in <module>
33 condb = create_connection()
34 if checkTableExists(condb, "naissances") == False:
---> 35 create_database(condb)
36 condb.close()
<ipython-input-17-4e8172277b2f> in create_database(connection)
29
30 def create_database(connection):
---> 31 execute_file_script(connection, "naissances.sql")
32
33 condb = create_connection()
<ipython-input-17-4e8172277b2f> in execute_file_script(dbcon, filename)
25 def execute_file_script(dbcon, filename):
26 sql_script_content = get_sql_script_content(filename)
---> 27 dbcon.command(sql_script_content)
28 dbcon.commit()
29
/usr/local/lib/python3.8/site-packages/pymonetdb/sql/connections.py in command(self, command)
143 """ use this function to send low level mapi commands """
144 self.__mapi_check()
--> 145 return self.mapi.cmd(command)
146
147 def __mapi_check(self):
/usr/local/lib/python3.8/site-packages/pymonetdb/mapi.py in cmd(self, operation)
238
239 self._putblock(operation)
--> 240 response = self._getblock()
241 if not len(response):
242 return ""
/usr/local/lib/python3.8/site-packages/pymonetdb/mapi.py in _getblock(self)
315 return self._getblock_socket() # control doesn't do block splitting when using a socket
316 else:
--> 317 return self._getblock_inet()
318
319 def _getblock_inet(self):
/usr/local/lib/python3.8/site-packages/pymonetdb/mapi.py in _getblock_inet(self)
321 last = 0
322 while not last:
--> 323 flag = self._getbytes(2)
324 unpacked = struct.unpack('<H', flag)[0] # little endian short
325 length = unpacked >> 1
/usr/local/lib/python3.8/site-packages/pymonetdb/mapi.py in _getbytes(self, bytes_)
343 count = bytes_
344 while count > 0:
--> 345 recv = self.socket.recv(count)
346 if len(recv) == 0:
347 raise OperationalError("Server closed connection")
KeyboardInterrupt:
%% Cell type:code id: tags:
``` python
def execute_db_command(connection, sql_command):
# create a cursor
cursor = connection.cursor()
# increase the rows fetched to increase performance (optional)
cursor.arraysize = 100
# execute the query
cursor.execute(sql_command)
# fetch results
result = cursor.fetchall()
# close cursor
cursor.close()
return result
def get_db_data(connection, y_axis):
return execute_db_command(connection, 'SELECT annee, {} FROM naissances'.format(y_axis))
condb = create_connection()
if checkTableExists(condb, "naissances") == False:
create_database(condb)
condb.close()
selector = pn.widgets.Select(name='y axis values', options=['nombre', 'taux'])
# fetch data
@pn.depends(selector.param.value)
def getplot(y_axis):
connection = create_connection()
data=get_db_data(connection, y_axis)
if y_axis == 'nombre':
y_axis_name='Nombre de naissance'
else:
y_axis_name='Taux de naissance'
df = pd.DataFrame(np.array(data), columns = [ 'annee', y_axis])
plot = figure(x_axis_label='annee',
y_axis_label=y_axis_name,
title="Naissances en france depuis 1982")
plot.line('annee', y_axis, source=df)
connection.close()
return plot
#graph
pn.Column(selector, getplot).servable()
#pn.panel(graph)
```
%% Output
---------------------------------------------------------------------------
OperationalError Traceback (most recent call last)
<ipython-input-16-16e6ce1dd3f9> in <module>
43
44 #graph
---> 45 pn.Column(selector, getplot).servable()
46 #pn.panel(graph)
/usr/local/lib/python3.8/site-packages/panel/layout/base.py in __init__(self, *objects, **params)
358 "as positional arguments or as a keyword, "
359 "not both." % type(self).__name__)
--> 360 params['objects'] = [panel(pane) for pane in objects]
361 elif 'objects' in params:
362 params['objects'] = [panel(pane) for pane in params['objects']]
/usr/local/lib/python3.8/site-packages/panel/layout/base.py in <listcomp>(.0)
358 "as positional arguments or as a keyword, "
359 "not both." % type(self).__name__)
--> 360 params['objects'] = [panel(pane) for pane in objects]
361 elif 'objects' in params:
362 params['objects'] = [panel(pane) for pane in params['objects']]
/usr/local/lib/python3.8/site-packages/panel/pane/base.py in panel(obj, **kwargs)
49 if kwargs.get('name', False) is None:
50 kwargs.pop('name')
---> 51 pane = PaneBase.get_pane_type(obj, **kwargs)(obj, **kwargs)
52 if len(pane.layout) == 1 and pane._unpack:
53 return pane.layout[0]
/usr/local/lib/python3.8/site-packages/panel/param.py in __init__(self, object, **params)
621 if object is not None:
622 self._validate_object()
--> 623 self._update_inner(self.eval(object))
624
625 @param.depends('object', watch=True)
/usr/local/lib/python3.8/site-packages/panel/param.py in eval(self, function)
654 args = (getattr(dep.owner, dep.name) for dep in arg_deps)
655 kwargs = {n: getattr(dep.owner, dep.name) for n, dep in kw_deps.items()}
--> 656 return function(*args, **kwargs)
657
658 def _update_pane(self, *events):
/usr/local/lib/python3.8/site-packages/param/parameterized.py in _depends(*args, **kw)
335 @wraps(func)
336 def _depends(*args,**kw):
--> 337 return func(*args,**kw)
338
339 deps = list(dependencies)+list(kw.values())
<ipython-input-16-16e6ce1dd3f9> in getplot(y_axis)
26 def getplot(y_axis):
27 connection = create_connection()
---> 28 data=get_db_data(connection, y_axis)
29
30 if y_axis == 'nombre':
<ipython-input-16-16e6ce1dd3f9> in get_db_data(connection, y_axis)
17
18 def get_db_data(connection, y_axis):
---> 19 return execute_db_command(connection, 'SELECT annee, {} FROM naissances'.format(y_axis))
20
21 selector = pn.widgets.Select(name='y axis values', options=['nombre', 'taux'])
<ipython-input-16-16e6ce1dd3f9> in execute_db_command(connection, sql_command)
7
8 # execute the query
----> 9 cursor.execute(sql_command)
10
11 # fetch results
/usr/local/lib/python3.8/site-packages/pymonetdb/sql/cursors.py in execute(self, operation, parameters)
163 query = operation
164
--> 165 block = self.connection.execute(query)
166 self._store_result(block)
167 self.rownumber = 0
/usr/local/lib/python3.8/site-packages/pymonetdb/sql/connections.py in execute(self, query)
138 def execute(self, query):
139 """ use this for executing SQL queries """
--> 140 return self.command('s' + query + '\n;')
141
142 def command(self, command):
/usr/local/lib/python3.8/site-packages/pymonetdb/sql/connections.py in command(self, command)
143 """ use this function to send low level mapi commands """
144 self.__mapi_check()
--> 145 return self.mapi.cmd(command)
146
147 def __mapi_check(self):
/usr/local/lib/python3.8/site-packages/pymonetdb/mapi.py in cmd(self, operation)
264 elif response[0] == MSG_ERROR:
265 exception, msg = handle_error(response[1:])
--> 266 raise exception(msg)
267 elif response[0] == MSG_INFO:
268 logger.info("%s" % (response[1:]))
OperationalError: SELECT: no such table 'naissances'
%% Cell type:code id: tags:
Column
[0] Select(name='y axis values', options=['nombre', 'taux'], value='nombre')
[1] ParamFunction(function)
``` python
```
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment