Python – SQLAlchemy – Oracle

SQLAlchemy to ORM (relacyjny maper) baz danych dla pythona, konkurencyjny względem SQLObject.

Object-relational mapping (ORM, O/RM, and O/R mapping) in computer software is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a “virtual object database” that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools...

Definicja przytoczona za – http://en.wikipedia.org/

Read more of this post

Python – PostgreSQL Database Backup Script

Simple script to backup some databases from PostgreSQL on unix\linux.


#!/usr/bin/env python
import os
import time

username = 'root'
defaultdb = 'postgres'
port = '5433'
backupdir='/www/backup/'
date = time.strftime('%Y-%m-%d')

#GET DB NAMES
get_db_names="psql -U%s -d%s -p%s --tuples-only -c '\l' | awk -F\| '{ print $1 }' | grep -E -v '(template0|template1|^$)'" % (username, defaultdb, port)

#MAKE BACKUP OF SYSTEMGRANTS
os.popen("pg_dumpall -p%s -g|gzip -9 -c > %s/system.%s.gz" % (port, backupdir, date))

#MAKING DB BACKUP
for base in os.popen(get_db_names).readlines():
        base = base.strip()
        fulldir = backupdir + base
        if not os.path.exists(fulldir):
                os.mkdir(fulldir)
        filename = "%s/%s-%s.sql" % (fulldir, base, date)
        os.popen("nice -n 19 pg_dump -C -F c -U%s -p%s %s > %s" % (username, port, base, filename))

Export Oracle Database to CSV

Export Oracle Database to CSV

#!/usr/bin/env python

import sys
import csv
import cx_Oracle

connection = raw_input("Enter Oracle DB connection (user/pass@database) : ")
orcl = cx_Oracle.connect(connection)
curs = orcl.cursor()

printHeader = True

sql = "select * from tab"
curs.execute(sql)

for row_data in curs:
 if not row_data[0].startswith('BIN$'):
 tableName = row_data[0]

 csv_file_dest = tableName + ".csv"
 outputFile = open(csv_file_dest,'w')
 output = csv.writer(outputFile, dialect='excel')
 sql = "select * from " + tableName
 curs2 = orcl.cursor()
 curs2.execute(sql)

 if printHeader:
 cols = []
 for col in curs2.description:
 cols.append(col[0])
 output.writerow(cols)

 for row_data in curs2:
 output.writerow(row_data)

 outputFile.close()

Pass

Test
Test

Przydatne Linki – Django

Django

Odliczanie Czasu W Pythonie – “Złapane W Sieci”

Odliczanie czasu w Pythonie – czasami jest przydatne.

from Tkinter import *
import time
import sys

class StopWatch(Frame):
""" Implements a stop watch frame widget. """
def __init__(self, parent=None, **kw):
Frame.__init__(self, parent, kw)
self._start = 0.0
self._elapsedtime = 0.0
self._running = 0
self.timestr = StringVar()
self.makeWidgets()

def makeWidgets(self):
""" Make the time label. """
l = Label(self, textvariable=self.timestr)
self._setTime(self._elapsedtime)
l.pack(fill=X, expand=NO, pady=2, padx=2)

def _update(self):
""" Update the label with elapsed time. """
self._elapsedtime = time.time() - self._start
self._setTime(self._elapsedtime)
self._timer = self.after(50, self._update)

def _setTime(self, elap):
""" Set the time string to Minutes:Seconds:Hundreths """
minutes = int(elap/60)
seconds = int(elap - minutes*60.0)
hseconds = int((elap - minutes*60.0 - seconds)*100)
self.timestr.set('%02d:%02d:%02d' % (minutes, seconds, hseconds))

def Start(self):
""" Start the stopwatch, ignore if running. """
if not self._running:
self._start = time.time() - self._elapsedtime
self._update()
self._running = 1

def Stop(self):
""" Stop the stopwatch, ignore if stopped. """
if self._running:
self.after_cancel(self._timer)
self._elapsedtime = time.time() - self._start
self._setTime(self._elapsedtime)
self._running = 0

def Reset(self):
""" Reset the stopwatch. """
self._start = time.time()
self._elapsedtime = 0.0
self._setTime(self._elapsedtime)

def callback():
print('Test menu')

def main():
root = Tk()
root.title('Python Timer')
# create a menu
menu = Menu(root)
root.config(menu=menu)

filemenu = Menu(menu)
menu.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="New", command=callback)
filemenu.add_command(label="Exit", command=root.quit)

helpmenu = Menu(menu)
menu.add_cascade(label="Help", menu=helpmenu)
helpmenu.add_command(label="About...", command=callback)

sw = StopWatch(root)
sw.pack(side=TOP)

Button(root, text='Start', command=sw.Start).pack(side=LEFT)
Button(root, text='Stop', command=sw.Stop).pack(side=LEFT)
Button(root, text='Reset', command=sw.Reset).pack(side=LEFT)
Button(root, text='Quit', command=root.quit).pack(side=LEFT)

root.mainloop()

if __name__ == '__main__':
main()

Powtórka z Pythona – Czyli Strony Które Warto Odwiedzić

  1. Non-Programmers Tutorial for Python – http://rupert.honors.montana.edu/~jjc/easytut/easytut/easytut.html
  2. Official Python Documentation – http://www.python.org/doc/current/
  3. Text Processing in Python -http://gnosis.cx/TPiP/
  4. Python Reference Manual – http://docs.python.org/ref/ref.html
  5. Python Imaging Library Handbook -http://www.pythonware.com/library/the-python-imaging-library.htm
  6. How to Think Like a Computer Scientist – Learning with Python – http://www.greenteapress.com/thinkpython
  7. Dive Into Python -http://diveintopython.org/
  8. Thinking in Python – http://mindview.net/Books/TIPython
  9. A Byte of Python – http://www.ibiblio.org/g2swap/byteofpython/read/
  10. Learning to Program - http://www.freenetpages.co.uk/hp/alan.gauld/
  11. Introduction to Programming using Python – http://www.pasteur.fr/formation/infobio/python/
  12. Python for Fun – http://www.ibiblio.org/obp/py4fun/
  13. Python 101 — Introduction to Python – http://www.rexx.com/~dkuhlman/python_101/python_101.html
  14. Python Short Course – http://www.wag.caltech.edu/home/rpm/python_course/
  15. The What, Why, Who, and Where of Python – http://www.networkcomputing.com/unixworld/tutorial/005/005.html
  16. Python Tutorial – http://www.python.org/doc/current/tut/tut.html
  17. Python Library Reference – http://www.python.org/doc/current/lib/lib.html
  18. Python Reference Manual – http://www.python.org/doc/current/ref/ref.html
  19. Python Cookbook - http://aspn.activestate.com/ASPN/Cookbook/Python
  20. Python 201 — (Slightly) Advanced Python Topics – http://www.rexx.com/~dkuhlman/python_201/python_201.html
  21. Tutorial – Embedded Python – http://www.ragestorm.net/tutorial?id=21
  22. Using Python for CGI programming – http://www.python.org/doc/essays/ppt/sd99east/tsld001.htm
  23. Extending and Embedding the Python Interpreter – http://www.python.org/doc/current/ext/ext.html
  24. Python GUI Programming – http://www.metaslash.com/brochure/tutorial/
  25. PyGTK 2.0 Tutorial – http://www.moeraki.com/pygtktutorial/pygtk2tutorial/
  26. Tkinter Life Preserver – http://python.org/doc/life-preserver/index.html
  27. An Introduction to Tkinter – http://www.pythonware.com/library/tkinter/introduction/index.htm
  28. PythonCard Documentation - http://pythoncard.sourceforge.net/walkthrough1.html
  29. CGI FAQ – http://starship.python.net/crew/davem/cgifaq/faqw.cgi?req=index
  30. Python: Interactive CGI Tutorial – http://www.cs.virginia.edu/~lab2q/lesson_1/
  31. Using Python for CGI programming – http://www.python.org/doc/essays/ppt/sd99east/
  32. Python course in Bioinformatics – http://www.pasteur.fr/recherche/unites/sis/formation/python/
  33. Socket Programming HOWTO – http://www.amk.ca/python/howto/sockets/sockets.html
  34. Regular Expression HOWTO – http://www.amk.ca/python/howto/regex/
  35. Python with COM – Get at your Office Data – http://starship.python.net/crew/pirx/spam7/
  36. The Document Object Model API – http://www.python.org/doc/current/lib/module-xml.dom.html
  37. The Django Book – http://www.djangobook.com

Debugowanie Aplikacji Django

djangoOd nie dawna mam “zaszczyt”  testowania aplikacji Django i pierwsze pytanie jakie postawiłem sobie było następujące:

W jaki sposób programiści aplikacji Django Debugują swoje aplikacje?

Najprościej zainstalować Django-Debug-Toolbar. Co należy zrobić?

  • Pobrać Django-Debug-ToolBar
  • Umieścić katalog debug_toolbar w katalogu projektu, lub  w dowolnym miejscu na dysku i dopisać lokalizację do  PYTHONPATH
  • W pliku settings.py naszego projektu szukamy MIDDLEWARE_CLASSES  i dodajemy
 'debug_toolbar.middleware.DebugToolbarMiddleware'
  • W tym samym pliku dodajemy konfigurację określającą wygląd panelu:
 DEBUG_TOOLBAR_PANELS = ( 'debug_toolbar.panels.version.VersionDebugPanel', 'debug_toolbar.panels.timer.TimerDebugPanel', 'debug_toolbar.panels.settings_vars.SettingsVarsDebugPanel', 'debug_toolbar.panels.headers.HeaderDebugPanel', 'debug_toolbar.panels.request_vars.RequestVarsDebugPanel', 'debug_toolbar.panels.template.TemplateDebugPanel', 'debug_toolbar.panels.sql.SQLDebugPanel', 'debug_toolbar.panels.signals.SignalDebugPanel', 'debug_toolbar.panels.logger.LoggingPanel', ) 
  • W pliku stetings.py do INSTALLED_APPS dodajemy
'debug_toolbar'
  • Dodajemy listę IP, które będą widziały panel. Dla localhosta:
 INTERNAL_IPS=['127.0.0.1:8000']'

Wygląd Panelu Administracyjnego przykładowej aplikacji wygląda jak poniżej:

debug

C.D.N

Follow

Otrzymuj każdy nowy wpis na swoją skrzynkę e-mail.