Sunday, November 28, 2010

Best Of Angelica Bella

Web Applications with Python, Apache and MySql

This weekend I was relatively rainy forced to stay at home and not having to do a beep ... sn I made a little hack I have already spoken with Python.Ne python, but most other times I look at it is more like me .. It 's great! Simple, fast, object-oriented (in Python everything is an object ...), but also has data structures that allow you to manipulate their contents with few lines of code (except one) unlike other languages \u200b\u200bthat it takes tens of lines ... I'm talking about structures such as dictionaries, tuples, lists and collections ... Documentatevi a bit ... Anyway the purpose of my post is to show you how to use python for web frameworks like without Zope, Django, WebWare .. But only volumes python, mysql and much loved, robust and secure Apache web server that has contributed heavily to the growth of the World Wide Web. And we'll see how easy it is to implement the MVC (Model View Controller) with this solution.
Here's what we need on the pc:
  • Apache2 Web Server MySql server
  • the apache module
  • mod_python for python library python MySQLdb
  • nn and of course if the Python interpreter installed on your system
all with a nice Install:
sudo apt-get install apache2 libapache2-mod-python, mysql-server , python-MySQLdb
I did not put in the command python usually already installed if not add it .. Obviously I'm assuming you have Ubuntu or a Debian derivative. Winblows if you go to Google to see how to install .. then I suggest you use the python plugin for eclipse PyDev that has code completion ee all other future profits (.. even if it lacks support for PSP, I'm not talking about playstation will explain later ... but I solved my building a plugin;)) Anyway here is the structure of the final project so there you an idea of \u200b\u200bwhere to place the file is if you use both eclipse and if you work directly in the directory with a text editor:

this course is the structure that I chose, but no one undertakes to respect it ... As you have guessed from the image put on a simple guestbook ... In the src folder there are the sources and everything will fall into the server folder Apache.Nella I put a backup folder resource to give directives to the apache configuration and the sql to generate the table on db.Il Ant build.xml file that you see I do not always created for a server to the user cp and launch the eclipse we do not use it all for our purposes (the Eclipse project ... but you can download from the link I give at the bottom of the post). In the src folder structure we have a package that contains the Python source code related to the model ( dto, dao etc.. you see that I have a strong influence Java ...) then index.py a file that acts as a controller and the pages in the folder psp PSP (Python Server Page) that form the view .... The PSP python are nothing more than a port (very limited) that are JSP to JAVA. That mix Python code in HTML in order to decide the logic of that rendering, but you will understand better read on (m or the big shot and some java guru is about to beat me, but mind you are my introductory tutorial for those who are beginners like I was and I'm not going to go down in the technical). To better understand what we're going to build and how the various components work together memorizzatevi the following scheme:


diagram is represented as a logical scheme of the CompoNet interact with each other after a http request from a client. On the right side of the diagram shows the directory where we will put our web project once complete or at least to test it with subdirectories and files. Try to explain the flow:
  • The client (the web broweser) requires the resource to the server index.py
  • the Apache server takes consider the request and because he was told that all requests for extension of the site. py must be eleaborate from mod_python passes the ball to him.
  • The python module then calls the resource index.py
  • Index.py decide, based on function, they need access to the model to save or read one or more belongings Dedica.py then called DedicaDao.py
  • DedicaDao. py using the MySQLdb python module (which I forgot sn shown) accesses the MySQL db and writes or reads data returning the result to index.py
  • Once processed the data, all at the mod_python Index.py returns saying that PSP developing and passing the necessary data
  • The mod_python PSP processes the generated html to be returned to the Apache server Apache
  • html returns received in response to the client
  • The client receiving the response with the HTML it renders in the finastra broweser.
diagram can be seen clearly with the MVC model since rappresetato dedicadao.py dedica.py and objects, the psp rapprestano layer and view the form index.py controller.Ben hours ago from fiddle around a bit. APACHE CONFIGURATION
Configuring Apache for saying that the project must use the mod_python and what resources will not make pubbliche.Quindi open with text editor the file: gedit / etc/apache2/sites-available / default and add the following lines:


As you can see are three directives directory: First Directive:
  • PYTHONPATH: where they are used to define the python modules (the *. py of our model) to use as a library to load the mod_python.
  • AddHandler: we said that the requests sent to PyGuestbook with. Py be the module to deal
  • PythonHandler python: python module to tell the handler to use the "publisher" (if you read the official documentation and understand better what that there are others)
  • PythonDebug We will put it to ON to tell the module that we are being development and present the error in the browser. In production is set to OFF in order to get the classic error 500 (Internal server error) in case of problems.
Second Directive:
  • say to apache qualsia must decline the request to the directory containing the libraries
Third Directive:
  • say to apache qualsia must decline the request to the folder containing your psp
course I have taken for assume that the folder where are the websites apache is / var / www / and you're on linux. If you are on other systems documentatevi on different path for the rest of the configuration is the same. Qualsisi configuration do you have to restart the server (and you will feel like on your skin even when you make changes to the site a few times it did), the command sudo / etc/init.d/apache2 restart
PREPARATION MYSQL
Now let us create a MySql db and table. Log in to mysql:
sudo mysql-u-p
enter your password and you provide the command-line mysql.
Create db with the command: create database
test_py;
move created in the database:
use test_py;
create the table we need:

DEVELOPMENT APPLICATION begin with the model that the data be treated. How did you know the creation of the table we have only one type of data that we create and then spends the 'python object that represents our information here is the code:

piergiuseppe82.guestbook.model Enter the code in the package. Each instance of this object will be used as a data transport object (DTO) between DedicaDao.py and index.py. Without this we will create the service object that will handle data access (DAO) on the db and then in the package insert piergiuseppe82.guestbook.model.dao DedicaDao.py:
As you can see the service object contains a method definition for each CRUD (Create Read Update Delete) we are going to do on the db, plus two private methods that are used to convert the records taken from the db in instances of objects Dedication.

be noted how python MySQLdb module is used for communicating with the MySQL server and other services for communicating with the latter. (Do not explain every line of code because it is not the purpose of the tutorial, if you are unsure what makes a particular line of code go to the official documentation of python.)

Now, we are actively linked to the Web application that is decides that the application must meet the following user requirements:

1.Insert a nickname to be saved in the dedication and maintain the authenticated user.
2.Insert and save on a new dedicated db where the user is already present prepolare the field with the nickname entered otherwise give an error message.
3.Visualuzzare the list of dedications, with access to the modification of any dedication and its possible elimination.
4.Editare a dedication and save it to db.
5.Eliminare dedication.

qnd bed now transformed by the requirements in web services in python code. So here below our index.py to put in the src folder:



As I mentioned above is the code from the controller and he will always be out an inquiry to respond to the browser (of course after the request has passed and made readable by apache mod_python). So understand how this works and makes you understand how to use everything and customize as you wish.

Now I have to explain how the communication between the mod_python index.py out our form.
First of all we talk about the urls that identify our services.
To invoke a service to our form we must enter into your browser:

http://localhost/PyGuestbook/index.py

where PyGuestbook is the folder to which puta apache / var / www / PyGuestbook containing our application which is also in the context of request. index.py is the form that we provided. In calls like that in the end only with the mod_python module, the default is to call the method defined in the module index index.py. If not defined returns a 404.

I say default because we have the possibility to specify the service.
For example if we want the new service dedicated to just call from the browser:

http://localhost/PyGuestbook/index.py/nuova_dedica

For every call to a method our controller to pass as a parameter the mod_python request (in the code if you see each method has a parameter which stands for Request req).

Doppo doing what is expected in response to the mod_python method is a string, which contains the code to generate html. In our case, however, we can do to generate mod_python same with the PSP (Python Server Pages), referring to his service.

comment code.

First we import the necessary modules like mod_python python modules and our model.

Then we have a number of private constants to the module that contains index.py strings used in code.

Going there is the configuraione dell'oggeto used for logging.

Finally, all methods invoked as services in the url of the request form index.py.
Let me explain in general what are the methods and as a requirement to be met. After I will explain in more detail, the better you understand how your code to comply with the requirement 2.

def index (req):
ago as an entry point to the module home page and in our case. It goes to meet the requirement that no one save in session dell'nickname used as access to the guestbook.

final nuova_dedica (req):
is invoked to access the service by inserting a new dedication and prepares necessary for the correct Displayed the psp response. Go to fulfill the requirement 2.

final salva_dedica (req, nickname, email, dedication):
is invoked in the form of post insertion of a new dedication which calls the DAO for the persistence of the latter. Then prepare the necessary for the rendering of the psp response. Go to fulfill the requirement 2.

final nuovo_nick (req):
this service is invoked from a link on the home page and takes care to clean the session of the previously inserted by nick index. It is part of a requirement
final lista_dediche (req):
deals call the dao to get all the dedications to save and advance psp as a parameter that takes care to see it. Go to fulfill requirement 3.

final elimina_dedica (req, id):
is responsible to call the dao to erase the inscription which has the id passed in the request. Go to fulfill the requirement 3 Pate, and meets the requirement 5.

final edit_dedica (req, id):
goes to prepare the necessary for the display of the inscription which has the id passed in the request by invoking the dao for this instance and then move on to the psp that deals with renderziarla in the edit form of a dedication. He goes to meet part of the requirements 3 and 4.

final aggiorna_dedica (req, id, nickname, email, dedication):
this service is called in after the edit form of a dedication by the dao and goes to update the dedication on db. Satisfies the requirement 4.

Now compredere how to better implement the code to process all components together so spiegherù dettaglioto a single use case. The inclusion of a new dedication.

The browser client side requires the insertion of a new service through a dedicated link on the homepage that points to the URL:
http://localhost/PyGuestbook/index.py/nuova_dedica

mod_python the answers because we want a *. py and specifically the form index.py occorge then we specified a service module that index.py nuova_dedica then goes to call the method with the same name as a parameter through the request.

Respond new method dedication:


What?
  • - logs the first entry to the method
  • -
  • recalls the session - is to set the defaul type of response, in this case text / html
  • after you go to prepare a template or a psp to develop the mod_python in our case the psp to show the form for entering the new dedication.
  • - Then prepare two variables will contain messages and any messages will contain the nickname nickname.
  • - Try to recall the user's nickname in the session made by index method and the sect in the variable.
  • - If you change your nickname is blank psp develop and prepare the message to be Displayed error message to the psp.
  • - So says all'oggeto psp to process the template, passing it a dictionary containing the variables needed.

We see the subcase where the nickname is blank, we said that the process goes to psp messages.psp message here is how it is made:


first we have a Directive psp psp inclusion of another in our case the Hedera. psp (containing the top generated html; bottom of the post will give you the psp). So for a psp uncludere Directive is:

\u0026lt;% @ include file = "nomedelfile.psp"%>

after the include directive, we have a scriptlet, or part of python code. It is enclosed in tags
\u0026lt;% .. %>

The code in question is to test the variable from the method nickname passatagli nuova_dedica index.py module. If this is not empty renders the contents of the variable preceded by the text Hello and followed by the new tag line, in short, the html to render the if statement if the condition is met. So to render the contents of a variable using the directive

\u0026lt;% = varname%>.

After you open and close the python code \u0026lt;%%> which may seem empty, but it is not. In reality there is the closure of the intent of the construct if (if you follow this tutorial then you have some experience in python and you understand what I'm talking about). In fact, no such termination or messages would be displayed if nickname is empty.

Hence, the Directive of the message passed to see them always as a parameter.

In the end there is another include directive, but in this case, the footer contains the bottom of the html code.


Now we move to another nickname in case that the variable is retrieved by the method Sesion nuova_dedica. In this case we have to draw the psp newDedica.psp said, here's how it is done:


contains besides as you see in the html header and footer for a form that allows you to enter the Username, Email and message of Dedication. The nickname is as you see prevalorizzato python with the directive to render the nickname of the variable passed as the run method of the object paramet psp mod_python.

Also note that where the form is posted

/ PyGuestbook / index.py / salva_dedica

Let's go with, let's say you fill up the form in the browser and press the Save dedication.

The post contained in the request comes to the method of the form salva_dedica index.py:


the method gets the request and notice in this case paramtri the method that in addition to the request also contains the names data to form fields. Indeed in this mod_python paremetri have entered the correct values \u200b\u200bwithout the need for us to go and retrieve dall'oggeto req.

makes the usual preparations to pass variables and PSQ to render. Then validate the data and if they do not comply with the condition to be exploited to change the psp to be rendered with that of prior view and enhances the value of the variable messages.
Otherwise it points to the Dao to the inclusion of the new dedication.
Once inserted, again via the dao, goes to retrieve the list of dedications to put them in variebile dedications to pass to the template.

Well let's say it went well then the psp tt processable listaDediche.psp:


liquids in the psp check first if the object is not empty lista_dediche dedication in case of success begins to render the table with the column names to the list and then loops for each devotes to see them go to insertion date, nickname, email and message. The last column is to add the link to the change and the elimination of the dedication passing as a parameter in the request id of the inscription in question.

Well I'm done and I hope that the explanation of this use case I have clarified the operation of all or how to use python for the web in its simplest form + observing the MVC pattern.

To test that there is copy the contents of folder src into / var / www / PyGuestbook

Maybe you can measure in solving some bugs that we are in If the user fails to comply with the navigation flow ..

Here are the contents of the PSP is not treated so far:

HEADER.PSP:



FOOTER.PSP:




INDEX.PSP



EDITDEDICA.PSP



and click here if The Eclipse project.


the next.

Saturday, November 27, 2010

Trucker Gay Beats Sydney

Thought liquid and 'collapse' of the mind

seems that the company starts to leave the mind before it sinks. A set of boredom, contempt for everything that happens in the so-called real time and slow the need for more strong to be there, where the event happens rejecting bureaucratic architecture of representation leads us to accelerate and facilitate the collapse of an ancient mind. Everything is initiating and facilitating a hyperbolic trend, leading to a perception of depth and intense that reveals an unexpected complexity and liquidity of world views (Gaetano Mirabella).

Thursday, November 18, 2010

Compatibility Couples Born On Same Day

Apple TV-like video streaming


( Vania Pavan )
The Apple TV is amazing!
Coast just over € 100, 1 to 5 € for the rental and 10 € on the purchase, and finally you can 'remove the external hard disk storage of films.
The movie must begin within 30 days from the rental and remain valid for 48 hours, you can 'buy to watch the movie without the restriction to the computer or Iphone Ipad. The films can also rent or buy from the TV connected to the Internet with a dedicated multimedia device without a set-up by the user.
There is no doubt that Apple offers a great service that more and more loyal users, or - depending on your point of view - they "forzino" to stay within their mechanisms.

Wednesday, November 10, 2010

Buring Knee Pain In The Night

change Marchel Duchamp, the star on his head and a kind of euphoria settled

Marcel Duchamp liked to say: "... So my art is to live, every second, every breath is a work of art that is not registered anywhere, that is neither visual nor cerebral. It 'a kind of euphoria settled "(1919).

Sunday, November 7, 2010

How To Solve Tally C0000005 Error

JPA with Spring, Hibernate JBoss

In this post I will explain the easiest way to use JPA with Spring in a web application that uses Struts2 like MVC framework.

Obviously in my case will extend Struts2Tutorial which if you read my previous tutorial about these technologies, you should know that I put in and attached to the post with the new implementations ...

will add a new contact management service that is providing the usual operations of insertion, searching, editing and deleting (aka CRUD) of a person and his contact details.

I will not go into technical, but see the steps to configure and use Spring with JPA on JBoss I'll assume some knowledge on these frameworks.

Before you configure the development environment.

Since the use of JPA and the transactions I had to use an application server that supports transactional without any configuration. JBOSS 4.2.2 GA so I chose my tutorial is based on the latter but you can choose any another. Fine

hours be sure to configure your project so that it can be compiled with the default profile jboss libraries.

WEB-INF/lib folder of the web project must be present the following libraries:

  • aopalliance.jar
  • commons-beanutils-1.7.0.jar commons-digester-
  • 2.0.jar commons-fileupload-1.2.1.jar
  • commons -logging-1.0.4.jar dom4j-1.6.1.jar
  • Freemarker-2.3.15.jar log4j-1.2.15.jar
  • mysql-connector-java-5.1.12-bin.jar
  • OGNL-2.7.3.jar slf4j-api-1.5.8.jar slf4j-
  • log4j12-1.5.0.jar spring-
  • aop.jar
  • spring-beans-2.5.6.jar
  • spring-context-2.5.6.jar
  • spring-core-2.5.6.jar spring-
  • jdbc.jar
  • spring-spring-orm.jar
  • tx.jar
  • spring-web-2.5.6.jar
  • Struts2-core-2.1.8.1.jar
  • Struts2-spring-plugin-2.1.8.1.jar
  • Struts2-tiles-plugin-2.1.8.1.jar
  • tiles-api-2.0.6.jar tiles-core
  • -2.0.6.jar tiles-jsp-2.0.6.jar
  • xwork-core-2.1.6-modified.jar
If you notice the ' Last library there is a modified because I had to change it for its incompatibility with jboss. However found the reason and the change in my previous post:

JBoss, Hibernate, JPA, Spring, Struts2: Javassist Enhancement failed



configured the working environment we pass to development.

The first thing to do is configure this integration ... As you know

JPA uses its own XML configuration file called persistence.xml then create a folder META-INF the root of the source (src / META-INF) and created inside the persistence.xml file with following content:



as you can see in our case, we leave it blank without any configuration to give only the name persistence-unit . We will make sure that spring to configure JPA with its configuration files.

Configure Now here is the spring ' applicationContext.xml necessary: \u200b\u200b



Then we configured in Spring XML as a bean dataSource which will handle communication with the db connection and instantiating the class of Spring DriverManagerDataSource and providing the necessary parameters. We

Defne another bean named EntityManagerFactory that instantiates a class of type LocalContainerEntityManagerFactoryBean . Such is the easiest to use Spring but it provides more depending on the architecture of your software and transaction management, you have chosen.
A bean that we have set the datasource previously defined. We told him what
jpaVendorAdapter used in our If a type HibernateJpaVendorAdapter because we use Hibernate as ORM. In the parameters of
jpaVendorAdapter we told him the type of database (MySQL), to automatically generate the bill and see the sql logs. As a last property of
EntityManagerFactory we have set jpaProperties setting the dialect to use and generate the necessary tables and delete db on each run and stop the application server. Of course I used this as a convenience so you do not have to rebuild the db tt for any modification;), but if you do not just put it as the parameter value update . With

we told Spring that will be defined by the transactional annotation classes.

In the end we have defined the type of bean TransactionManager JpaTransactionManager that handles the transaction, saying that is the ' EntityManagerFactory namely that you created earlier.

As you can see tt the configuration file is in the JPA configuration of Spring. The rest you see in the file does not center with JPA, but if you want to know what good look at my previous post.

Finally to complete the setup we have to insert the filter OpenEntityManagerInViewFilter in web.xml

The filter is used to map to which requests must instantiate the Spring entityManager. Here is the updated web.xml content:




Now for the data model and from now on, given that the aim was to show how to integrate JPA with Spring, I will be less descriptive, except for several precautions.
The data that we will manage are Person and Address. Where a person can have multiple addresses. Here are the classes:

Persona.java


As you can see is a simple Pojo whose attributes id, name, and a list of addresses. We used to map the location of the JPA annotations, I'll go further to a general review the official documentation: @ Entity
  • we told him that is on a separate db and in this case (not spqcificando table) will be created or otherwise mapped to a table with name Person.
  • @ Id we said that the attribute is the primary key.
  • @ GeneratedValue used to define the strategy for the generation of id in our case car, that will generate them in the db.
  • @ Column indicates that the attribute is a field in the table
  • @ OneToMany we have defined a one to many association.
  • @ JoinTable used to say that the association will use a table join
Recapito.java


There are the same except annotation @ ManyToOne indicating a one to many association and joinTable pointing to the same table join pima.

The result of the model data to db is as follows:


Defined model PersonaDao pass the class. Here's the interface:


then the interface provides the following methods:
  • save or change a person
  • removal of a person looking for a person
  • recovery of all persons
  • adding an address to a Perona
  • remozione an address
Given the simplicity of the model I created for a single dao Person for delivery. And here is its implementation
PersonaDaoImpl:


Before describing another look at the rows from 29 to 34 we defined the entityManager and its set method which will be used by Spring to set the entityManager in the configuration file . This setting will be done by Spring as we put on the method, the annotation @ PersistenceContext .

careful to line 25 then there is the annotation @ Transactional . M ettendola like this case as an annotation of class we told Spring that any method defined in it is transactional. That is, each transaction starts and ends and out of respect to the invocation method. But we can also define a method-level transaction using the annotation as annotation method.
In any case it is said that the transactional is defined in the dao, but it can also be defined in a class that calls the dao (liquids at even higher) in a class that acts as a business-logic or domain of the service.

As you can see the entity manager provides access methods to read and write to db as persist (new object), merge (update an object), find (reading an object) to select CreateQuery details etc. ... but there are others.

last thing to pay attention to the implementation of methods that access in writing. Make sure that the first well to continue or modify an object that is fully consistent with all other objects that it has as attributes. Now here's the

ContattiBl ie the class which is the domain or business logic of the service contacts and urilizza inside PersonaDao:


In the project I've used it recalled in Struts2 action but this part of the little man you now should be in control of thanks to my Struts2 tutorial: P You can download the project here without a library.