Re: python question

  • From: "Octavian Rasnita" <orasnita@xxxxxxxxx>
  • To: <programmingblind@xxxxxxxxxxxxx>
  • Date: Sat, 20 Dec 2008 23:41:09 +0200

(long)
Oh yes, but most programmers don't need to work in very many languages and it is much more productive to use an ORM.

For example, if somebody uses a form for selecting some records from a database and print them in a table based on some conditions, if the programmer would use SQL directly, he would need to do many "if" statements for testing each condition, then add a new piece to the SQL string, for selecting, or for ordering the results, or for limiting the number of selected rows, and the code would look very chaotic. And of course, the program would work for a single database type only.

If the programmer would use an ORM, the same programming code would work with MySQL, PostgreSQL, Oracle or any other supported database by that ORM. The programmer would need just to change the line that makes the connection to the database, so a database change would be very easy.

The good ORMS also have other features, like the possibility of creating the database from the schema for that database which is used by the ORM, so a user could change the schema, and with a simple program or command line he could change the database structure (the structure of the tables), or he can create a database for another database type.

Here is an example for a program that selects the records from a database based on some variables that might or might not be sent by a form, when using the ORM named DBIx::Class in a Catalyst framework-based application.

This page will be accessed with an url like:
http://www.site.com/books/search/3

where that "3" means that the results should be grouped in pages with say 50 results per page, and that we want to display the page number 3:

sub search : Local {
my ($self, $c, $page) = @_;

#The variables that could be used for searching the database
my $year = $c->req->param('year');
my $title = $c->req->param('title');
my $author = $c->req->param('author');

#The results set:
my $books = $c->model("DB::Books")->search;

#Add conditions to this results set:
$books = $books->search({year => $year}) if $year;
$books = $books->search({title => {-like => "%$title%"}}) if $title;
$books = $books->search({author => {-like => "%$author%"}}) if $author;

#Store the results object and the data pager in the stash variables for using them in the template:
$c->stash->{pager} = $books->pager;
$c->stash->{books} = [$books->all];
}

That's the entire programming code needed
The template that displays the result could contain something like:

<table>
<tr><th>Title</th>
<th>Author</th>
<th>Appearrence year</th></tr>
[% FOREACH book IN books %]
<tr><td>[% book.title %]</td>
<td>[% book.author %]</td>
<td>[% book.year %]</td></tr>
[% END %]
</table>

And this template could also contain links to the same url, but instead of the current page (3), it could contain the variables like pager.previous_page or pager.next_page, or it could also show the number of total books found as pager.total_entries or the number of the first and last books found on this page as pager.first and pager.last.

This way, with only a few short lines of code, the programmer can write a code that would work on more database types, and the program would be much clearer and easier to maintain than one that would require concatenating strings for composing an SQL query. The query to the database will be made only when the template will be processed, not before, even it seems that the code that searches the database is made before, so the database will be accessed only when somebody will access this page and if the template would need to display the results.

To create the database schema that would be saved on the disk it is needed just a command line. In this case that DB::Books means that the model of this application is named "DB" and "Books" is just a table class - a perl module that describe the table named "books" which can be created automaticly. The schema of this database could be also used outside of the application, so the programmer could make an external program that use it for sending email to a list of users, or other long-lasting processes.

This program is a higher level programming, but even higher level would be possible if using a good ORM. For example, the programmer could choose to use a form manager like HTML::FormFu that could require much less work but with much more effects. The forms in that case wouldn't need to be defined in the HTML template but in a simple configuration file that could contain not only the properties for creating the form, but some requirements like the length of a field, or the characters it can contain, or if the field should contain an email address, or an URL, or if the spaces should be stripped from that field, or only the spaces at the edges of it.... but only the needed requirements should be specified. And that configuration file could also define some fields of a certain type that don't exist, for example a field that will create 3 combo boxes automaticly that will be filled with the days of the month, the month names and the years, with some options for each of these. And of course HTML::FormFu supports localization, so the fields can be localized to appear in more languages if necessary.

And if the user doesn't fill a required field, or fills it with something not valid, the program will automaticly prompt the user with the same form already filled, specifying for each field what was the error. And HTML::FormFu offers some defaults error messages (that have localization defaults for more languages) or the user could specify a custom error message in case a requirement was not met.

Such a configuration file with a certain form could be used in more pages, without needing to use the same specifications for more time, and they could include other configuration files with some groups of fields which are used in more forms.

Well, if using HTML::FormFu and DBIx::Class, the user should need to write too much code for creating or updating a database. He must do only something like the code below for updating a book with ID=100:

Access:
http://www.site.com/books/update/100

sub update : Local : FormConfig {
my ($self, $c, $id) = @_;

#Search this book in the database:
my $book = $c->model("DB::Books")->find($id);

my $form = $c->stash->{form};

if ($form->submitted_and_valid) {
$form->model->update($book);
#Here do a redirect to another page, or something else
}
else {
$form->model->default_values($book);
}
}

That's all. And for creating a new book record, the programmer should only use $form->model->create($new_book); or even less code if the configuration file for that form also contains the table default table name...

The program knows to create the form, to validate it, to generate the needed SQL for the currently used database type, to do update, or insertion, it also can automaticly generate a DateTime object from those 3 combo boxes with the year, month and day, object that would have very many useful methods and properties, and do really very many other things.

So using any other language than perl, it should be able to do these things, because otherwise its productivity would be much lower.

I know that most users that start learning perl start by learning to create CGI scripts, use the CGI.pm module, use the DBI module directly, and don't even think to start using a templating system or a form validator, but that perl is not the currently used perl in production. The perl programmers that need to create a good code use to use much more other tools than the low level and well known perl modules promoted by the existing perl books. And I am sure it is the same for other languages, but I just want to found if those tools like the ORMS, the forms managers, the templating systems, the frameworks are at least as good as those offered for perl, because otherwise is very unimportant the language used.

You've seen the code needed to update a database above. Well, that is an object-oriented code that could have been written in any other language, because it is so small that it doesn't really matter if it needs indentation or not, or if it uses blocks created with braces, but I want to be sure that other languages also offer tools that would allow me to use a code like this, or even better.

And when doing this, the so called advantages of many languages disappear, and I am talking about the fact that the objects can be created easier in the language X or Y, or that the language X offer a native support for this and that feature, because all of these are already offered by a good framework and much more.

Octavian

----- Original Message ----- From: "Ken Perry" <whistler@xxxxxxxxxxxxx>
To: <programmingblind@xxxxxxxxxxxxx>
Sent: Saturday, December 20, 2008 9:10 PM
Subject: RE: python question




Good luck but the reason I don't like such constructs is you have to learn
something different for every coding language you use. Using something like
the mysql connector or sqlite3 libraries you only have to learn to connect
to a database and use regular sql statements thus you learn once and use in
many languages.  Sure it's easier to use an ORM if you're stuck in one
language but if you actually code in multiple languages you will find
porting what you know is harder.

Ken

-----Original Message-----
From: programmingblind-bounce@xxxxxxxxxxxxx
[mailto:programmingblind-bounce@xxxxxxxxxxxxx] On Behalf Of Octavian Rasnita
Sent: Saturday, December 20, 2008 4:06 AM
To: programmingblind@xxxxxxxxxxxxx
Subject: Re: python question

By ORM I ment Object-relational mapping.

With other words, I want to be able to access a MySQL, Oracle, PostgreSQL or

even SQLite database with objects, without needing to write SQL code at all.

I think it would be more simple to do something like:

db = TheORMName.connect("mysql", "databaseName", "user", "password")

recordset = db.table("testTable").search(id=123)

print(recordset.first.age)

recordset.update(name="My Name", age=55)

or putting the name of the dictionary in place of those fields, than
composing an SQL query based on different conditions.

I hope to find an ORM that can work with primary keys made of multiple
columns, that can do table joins and allow using operators like "like" and
other simple features like these...

Octavian

----- Original Message ----- From: "Ken Perry" <whistler@xxxxxxxxxxxxx>
To: <programmingblind@xxxxxxxxxxxxx>
Sent: Saturday, December 20, 2008 3:36 AM
Subject: RE: python question


Well since ORM has all these following meanings
ORM is an acronym for:

Object role modeling
Object-relational mapping
Operational Risk Management a U.S. Navy concept for safety in operations
planning
Online research methods
Orosomucoid
Outsourcing Relationship Management
Online Reputation Management

ORM is also:

the IATA airport code for Sywell Aerodrome in Northamptonshire, England


I am not sure exactly what you want.  I mean you mentioned a lot of
database
mapping libraries so I am hoping that is what you are looking for. We use
sqlite3 for our db only because it has some easy ways to just request
whole
tables into dictionaries in python.  I am not sure if you would consider
doing sql requests and having it auto port it into a dictionary an ORM but
to each their own.

Ken
-----Original Message-----
From: programmingblind-bounce@xxxxxxxxxxxxx
[mailto:programmingblind-bounce@xxxxxxxxxxxxx] On Behalf Of Octavian
Rasnita
Sent: Friday, December 19, 2008 5:01 PM
To: programmingblind@xxxxxxxxxxxxx
Subject: Re: python question

Hmm, is there an ORM for python that has the same name as the SQLite
command

line client?

Octavian

----- Original Message ----- From: "Ken Perry" <whistler@xxxxxxxxxxxxx>
To: <programmingblind@xxxxxxxxxxxxx>
Sent: Friday, December 19, 2008 10:58 PM
Subject: RE: python question



We use sqlite3

Ken

-----Original Message-----
From: programmingblind-bounce@xxxxxxxxxxxxx
[mailto:programmingblind-bounce@xxxxxxxxxxxxx] On Behalf Of Jim Dunleavy
Sent: Friday, December 19, 2008 4:59 AM
To: programmingblind@xxxxxxxxxxxxx
Subject: Re: python question

Hi,

SQLAlchemy seems to have the most features.
It's the default ORM for the TurboGears framework.

--Jim

----- Original Message -----
From: Octavian Rasnita <orasnita@xxxxxxxxx>
To: <programmingblind@xxxxxxxxxxxxx>
Sent: Thursday, December 18, 2008 11:50 AM
Subject: Re: python question


Ok, thanks.

Even though it requires a few more keywords, at least it doesn't require
quoting the keys of the dictionary.

I am searching for information about a good ORM in python, but what I
found
so far wasn't too impressive.
Does anyone know a really good ORM in python like DBIx::Class or
Rose::DB::Object in perl?

I found that for python there are more ORMS like: SQLObject, Axiom,
Bazaar
ORM, DbObj, Dejavu, forgetSQL, MiddleKit, Modeling Object-Relational
Bridge,
Object Relational Membrame, PyDo, SQLAlchemy, Storm... which of them do
you
think it is the best?

Thanks.

Octavian

----- Original Message -----
From: "Jamal Mazrui" <empower@xxxxxxxxx>
To: <programmingblind@xxxxxxxxxxxxx>
Sent: Thursday, December 18, 2008 12:45 AM
Subject: Re: python question


> Here is a Python 3 version.
> Jamal
>
> d = dict(John = 40, Michael = 40, Joe = 30)
> l = sorted(d.keys(), reverse = True)
> l = sorted(l, key = lambda k: d[k])
> for k in l: print(k + ', ' + str(d[k]))
>
>
> On Wed, 17 Dec 2008, Octavian
> Rasnita wrote:
>
>> Date: Wed, 17 Dec 2008 22:52:20 +0200
>> From: Octavian Rasnita <orasnita@xxxxxxxxx>
>> Reply-To: programmingblind@xxxxxxxxxxxxx
>> To: programmingblind@xxxxxxxxxxxxx
>> Subject: Re: python question
>>
>> Thank you for your answer, but I couldn't run it with python 3.
>>
>> I have re-formatted the print statement which in python 3 is a
function,
>> but
>> I don't know how to solve the other error that appeared.
>>
>> The code is:
>>
>> hash = {'John': 40, 'Michael': 40, 'Joe': 30}
>> keys = sorted(hash.keys(), reverse = True)
>> keys = sorted(keys, lambda x, y: cmp(hash[x], hash[y]))
>> for key in keys: print(key + ', ' + str(hash[key]))
>>
>> And the error is:
>>
>> Traceback (most recent call last):
>> File "srt.py", line 3, in <module>
>> keys = sorted(keys, lambda x, y: cmp(hash[x], hash[y]))
>> TypeError: must use keyword argument for key function
>>
>> Thanks.
>>
>> Octavian
>>
>> ----- Original Message -----
>> From: "Jamal Mazrui" <empower@xxxxxxxxx>
>> To: <programmingblind@xxxxxxxxxxxxx>
>> Sent: Wednesday, December 17, 2008 10:18 PM
>> Subject: RE: python question
>>
>>
>> > I'm not an advanced Python user, so there may be more efficient or
>> > elegant
>> > solutions.  The code below is a Python 2.5 equivalent.
>> >
>> > Jamal
>> >
>> > hash = {'John': 40, 'Michael': 40, 'Joe': 30}
>> > keys = sorted(hash.keys(), reverse = True)
>> > keys = sorted(keys, lambda x, y: cmp(hash[x], hash[y]))
>> > for key in keys: print key + ', ' + str(hash[key])
>> >
>> > -----Original Message-----
>> > From: programmingblind-bounce@xxxxxxxxxxxxx
>> > [mailto:programmingblind-bounce@xxxxxxxxxxxxx] On Behalf Of
>> > Octavian
>> > Rasnita
>> > Sent: Wednesday, December 17, 2008 8:40 AM
>> > To: programmingblind@xxxxxxxxxxxxx
>> > Subject: Re: python question
>> >
>> > The Windows msi installer for python from python.org contains a >> > chm
>> > help
>> > file for python 3, or at least this is how it is named.
>> >
>> > I haven't started to read it though.
>> >
>> > But I have a question regarding python.
>> >
>> > I have started to read the book "Perl to python migration" hoping
>> > to
>> > understand it better, but I am pretty confused of how python does
>> > the
>> > sorting, or at least about how it is explained in that book that
might
>> > be
>> > old, because it talks about python 2.0.
>> >
>> > For example, if I have a perl hash, or python dictionary like:
>> >
>> > my %hash = (Joe => 30, John => 40, Michael => 40);
>> >
>> > and I want to sort it for example by the values of the hashin
>> > increasing
>> > order, then by the keys of the hash in decreasing order, in perl I
>> > would
>> > need to do just:
>> >
>> > foreach my $key(sort {$hash{$a} <=> $hash{$b} or $b cmp $a} keys
%hash)
>> > {
>> > print "$key, $hash{$key}\n"; }
>> >
>> > This would print:
>> > Joe, 30
>> > Michael, 40
>> > John, 40
>> >
>> > Can you tell me how to do this in python? I hope there are newer
>> > ways
>> > of
>> > doing this more easier than what I read in that book.
>> >
>> > And I would also like to know which is the prefered ORM, the
>> > prefered
>> > templating systems, form manager(s), web framework... (although I
think
>> > it
>> > is Zope), so if you have used them, please tell me.
>> >
>> > Octavian
>> >
>> > ----- Original Message -----
>> > From: <james.homme@xxxxxxxxxxxx>
>> > To: <programmingblind@xxxxxxxxxxxxx>
>> > Sent: Wednesday, December 17, 2008 2:29 PM
>> > Subject: RE: python question
>> >
>> >
>> >> Hi,
>> >> Along those lines, does anyone know if any of the Python
documentation
>> > on
>> >> http://www.nonvisualdevelopment.org talks about 3.0?
>> >>
>> >> Thanks.
>> >>
>> >> Jim
>> >>
>> >> James D Homme, Usability Engineering, Highmark Inc.,
>> >> james.homme@xxxxxxxxxxxx, 412-544-1810
>> >>
>> >> "The difference between those who get what they wish for and >> >> those
who
>> >> don't is action. Therefore, every action you take is a complete
>> >> success,regardless of the results." -- Jerrold Mundis
>> >> Highmark internal only: For usability and accessibility:
>> >> http://highwire.highmark.com/sites/iwov/hwt093/
>> >
>> > __________
>> > View the list's information and change your settings at
>> > //www.freelists.org/list/programmingblind
>> >
>> >
>> > __________
>> > View the list's information and change your settings at
>> > //www.freelists.org/list/programmingblind
>> >
>>
>> __________
>> View the list's information and change your settings at
>> //www.freelists.org/list/programmingblind
>>
> __________
> View the list's information and change your settings at
> //www.freelists.org/list/programmingblind
>

__________
View the list's information and change your settings at
//www.freelists.org/list/programmingblind




----------------------------------------------------------------------------
"Information in this email (including attachments) is confidential.
It is intended for receipt and consideration only by the intended
recipient.
If you are not an addressee or intended recipient, any use,
dissemination,
distribution, disclosure, publication or copying of information contained
in
this email is strictly prohibited.  Opinions expressed in this email may
be
personal to the author and are not necessarily the opinions of the HSE.

If this email has been received by you in error we would be grateful if
you
could immediately notify the ICT Service Desk by telephone at +353 1
6352757

or by email to service.desk@xxxxxxxxxxxx and thereafter delete this
e-mail from your system"


----------------------------------------------------------------------------
__________
View the list's information and change your settings at
//www.freelists.org/list/programmingblind

__________
View the list's information and change your settings at
//www.freelists.org/list/programmingblind


__________
View the list's information and change your settings at
//www.freelists.org/list/programmingblind

__________
View the list's information and change your settings at
//www.freelists.org/list/programmingblind


__________
View the list's information and change your settings at
//www.freelists.org/list/programmingblind

__________
View the list's information and change your settings at
//www.freelists.org/list/programmingblind


__________
View the list's information and change your settings at //www.freelists.org/list/programmingblind

Other related posts: