Web2py – Adding Ajax Effects

Web2py – Adding Ajax Effects ”; Previous Next In this chapter, we will discuss examples of integration of jQuery plugins with web2py. These plugins help in making forms and tables more interactive and friendly to the user, thus improving the usability of your application. In particular, we will learn how to improve the multi-select drop-down with an interactive add option button, how to replace an input field with a slider, and how to display tabular data using jqGrid and WebGrid. Although web2py is a server-side development component, the welcome scaffolding app includes the base jQuery library. This scaffolding web2py application “welcome” includes a file called views/web2py_ajax.html. The contents of the view are as follows − <script type = “text/javascript”><!– // These variables are used by the web2py_ajax_init function in web2py_ajax.js (which is loaded below). var w2p_ajax_confirm_message = “{{= T(”Are you sure you want to delete this object?”)}}”; var w2p_ajax_disable_with_message = “{{= T(”Working…”)}}”; var w2p_ajax_date_format = “{{= T(”%Y-%m-%d”)}}”; var w2p_ajax_datetime_format = “{{= T(”%Y-%m-%d %H:%M:%S”)}}”; var ajax_error_500 = ”{{=T.M(”An error occured, please [[reload %s]] the page”) % URL(args = request.args, vars = request.get_vars) }}” //–></script> {{ response.files.insert(0,URL(”static”,”js/jquery.js”)) response.files.insert(1,URL(”static”,”css/calendar.css”)) response.files.insert(2,URL(”static”,”js/calendar.js”)) response.files.insert(3,URL(”static”,”js/web2py.js”)) response.include_meta() response.include_files() }} The file consists of implementation of JavaScript and AJAX implementation. web2py will prevent the user from using other AJAX libraries such as Prototype, ExtJS, because it is always observed that it is easier to implement such libraries. JQuery Effects The default rendering of <select multiple = “true”>..</select> is considered not so intuitive to use, in particular, when it is necessary to select non-contiguous options. This can not be called as an HTML shortcoming, but a poor design of most of the browsers. The presentation of the multiple select can be overwritten using JavaScript. This can be implemented using jQuery plugin called jquery.multiselect.js. For this, a user should download the plugin jquery.muliselect.js from http://abeautifulsite.net/2008/04/jquery-multiselect, and place the corresponding files into static/js/jquery.multiselect.js and static/css/jquery.multiselect.css. Example The following code should be added in the corresponding view before {{extend ‘layout.html’}} {{ response.files.append(”https://ajax.googleapis.com/ajax /libs/jqueryui/1.8.9/jquery-ui.js”) response.files.append(”https://ajax.googleapis.com/ajax /libs/jqueryui/1.8.9/themes/ui-darkness/jquery-ui.css”) response.files.append(URL(”static”,”js/jquery.multiSelect.js”)) response.files.append(URL(”static”,”css/jquery.multiSelect.css”)) }} Place the following after {{extend ”layout.html”}} − <script> jQuery(document).ready(function(){jQuery(”[multiple]”).multiSelect();}); </script> This will help to style multiselect for the given form Controller def index(): is_fruits = IS_IN_SET([”Apples”,”Oranges”,”Bananas”,”Kiwis”,”Lemons”], multiple = True) form = SQLFORM.factory(Field(”fruits”,”list:string”, requires = is_fruits)) if form.accepts(request,session):response.flash = ”Yummy!” return dict(form = form) This action can be tried with the following view − {{ response.files.append(”https://ajax.googleapis.com/ajax /libs/jqueryui/1.8.9/jquery-ui.js”) response.files.append(”https://ajax.googleapis.com/ajax /libs/jqueryui/1.8.9/themes/ui-darkness/jquery-ui.css”) response.files.append(URL(”static”,”js/jquery.multiSelect.js”)) response.files.append(URL(”static”,”css/jquery.multiSelect.css”)) }} {{extend ”layout.html}} <script> jQuery(document).ready(function(){jQuery(”[multiple]”). multiSelect();}); </script> {{= form}} The screenshot of the output is as follows − Some of the useful Jquery events are listed in the following table − Sr.No. Event & Usage 1 onchange to be run when the element changes 2 onsubmit to be run when the form is submitted 3 onselect to be run when the element is selected 4 onblur to be run when the element loses focus 5 onfocus to be run when the element gets focus JQuery and Ajax-jqGrid jqGrid is an Ajax-enabled JavaScript control built on jQuery that provides a solution for representing and manipulating tabular data. jqGrid is a client-side solution, and it loads data dynamically through Ajax callbacks, thus providing pagination, search popup, inline editing, and so on. jqGrid is integrated into PluginWiki, but, here, we discuss it as a standalone for web2py programs that do not use the plugin. jqGrid deserves a book of its own but here we will only discuss its basic features and simplest integration. The syntax of jqGrid will be as follows − def JQGRID( table, fieldname = None, fieldvalue = None, col_widths = [], colnames = [], _id = None, fields = [], col_width = 80, width = 700, height = 300, dbname = ”db” ): Print Page Previous Next Advertisements ”;

Web2py – Services

Web2py – Services ”; Previous Next web2py provides support for various protocols like XML, JSON, RSS, CSV, XMLRPC, JSONRPC, AMFRPC, and SOAP. Each of those protocols is supported in multiple ways, and we make a distinction between − Rendering the output of a function in a given format. Remote Procedure Calls. Rendering a Dictionary Consider the following code which maintains the count of the sessions. def count(): session.counter = (session.counter or 0) &plus; 1 return dict(counter = session.counter, now = request.now) The above function increases the number of counts as and when the user visits the page. Suppose the given function is defined in “default.py” controller of web2py application. The page can be requested with the following URL − http://127.0.0.1:8000/app/default/count web2py can render the above page in different protocols and by adding extension to the URL, like − http://127.0.0.1:8000/app/default/count.html http://127.0.0.1:8000/app/default/count.xml http://127.0.0.1:8000/app/default/count.json The dictionary returned by the above action will be rendered in HTML, XML and JSON. Remote Procedure Calls web2py framework provides a mechanism which converts a function into a web service. The mechanism described here differs from the mechanism described before because − Inclusion of arguments in function. The function must be defined in a model. It enforces a more strict URL naming convention. It works for a fixed set of protocols and it is easily extensible. To use this feature it is necessary to import and initiate a service object. To implement this mechanism, at first, you must import and instantiate a service object. from gluon.tools import Service service = Service() This is implemented in the “db.py” model file in the scaffolding application. Db.py model is the default model in web2py framework, which interacts with the database and the controller to achieve the desired output to the users. After implementing, the service in model can be accessed from the controllers as and when required. The following example shows various implementations of remote procedure calls using web services and many more. Web Services Web Services can be defined as a standardized way of integrating Web-based applications using the protocols like XML, SOAP, WSDL and UDDI. web2py supports most of them, but the integration will be quite tricky. Consuming a web2py JSON service with jQuery There are many ways to return JSON form web2py, but here we consider the case of a JSON service. For example − def consumer():return dict()@service.json def get_days():return [“Sun”, “Mon”, “Tues”, “Wed”, “Thurs”, “Fri”, “Sat”] def call():return service() Here, we observe that − the function just returns an empty dictionary to render the view, which will consume the service. get_days defines the service, and the function call exposes all registered services. get_days does not need to be in the controller, and can be in a model. call is always in the default.py scaffolding controller. View with the consumer actions are as follows − {{extend ”layout.html”}} <div id = “target”></div> <script> jQuery.getJSON(“{{= URL(”call”,args = [”json”,”get_days”])}}”, function(msg){ jQuery.each(msg, function(){ jQuery(“#target”). append(this &plus; “<br />”); } ) } ); </script> The first argument of jQuery.getJSON is the URL of the following service − http://127.0.0.1:8000/app/default/call/json/get_days This always follows the pattern − http://<domain>/<app>/<controller>/call/<type>/<service> The URL is in between {{…}}, because it is resolved at the server-side, while everything else is executed at the client-side. The second argument of jQuery.getJSON is a callback, which will be passed the JSON response. In this case, the callback loops over each item in the response (a list of week days as strings), and appends each string, followed by a <br/> to the <div id = “target”>. In this way, web2py manages implementation of web services using jQuery.getJSON. Print Page Previous Next Advertisements ”;

Web2py – Views

Web2py – Views ”; Previous Next web2py framework uses Models, Controllers and Views in its applications. It includes a slightly modified Python syntax in the Views for more readable code without any restriction as imposed on proper Python usage. The main purpose of a web2py View is to embed the python code in an HTML document. However, it faces some issues, which are as follows − Escaping of embedded python code in an HTML document. Following indentation based on Python, which may affect HTML rules. To escape with the problems, web2py uses delimiters {{..}} in the view section. The delimiters help in escaping the embedded python code. It also helps in following the HTML rules of indentation. The code included within {{..}} delimiters include unintended Python code. Since Python normally uses indentation to delimit blocks of code, the unintended code within the delimiters should be maintained in proper way. To overcome this problem, web2py uses the “pass” keyword. The code block beginning with a line terminates with a colon and ends with a line beginning with pass. Note − pass is a Python keyword, it is not a web2py keyword. The following code shows the implementation of pass keyword − {{ if num > 0: response.write(”positive number”) else: response.write(”negative number”) pass }} HTML Helpers web2py includes helper class which can be used to build HTML programmatically. It corresponds to the HTML tags, termed as “HTML helpers”. For example − [(A(”Home”, _href = URL(”default”, ”home”)), False, None, []), …] Here, A is the helper corresponding to the anchor <a> tag of HTML. It builds the HTML anchor <a> tag programmatically. HTML helpers consists of two types, namely positional and named arguments. Positional arguments are interpreted as objects contained between the HTML open and close tags. Named arguments begins with an underscore are interpreted as HTML tag. Helpers are also useful in serialization of strings, with the _str_ and xml methods. For example − >>> print str(DIV(“hello world”)) Output <div> hello world </div> Note − HTML helpers provide a server-side representation of the Document Object Model (DOM). XML Helpers XML is termed as an object, which encapsulates text that should not be escaped. The text may or may not contain valid XML. For example, for the below mentioned code, it could contain JavaScript. >>> print XML(”<script>alert(“unsafe!”)</script>”) Output <script> alert(“unsafe!”)</script> Built-in Helpers There are many built-in helpers used in web2py. Some of the HTML built-in helpers are listed as below. Name Usage Example A This helper is used to build links. It corresponds to the anchor tag [ (A(”Home”, _href = URL(”default”, ”home”)), False, None, []), …] B This helper helps in making the contents of the text, bold. B(”<hello>”, XML(”<i>world</i>”), _class = ”test”, _id = 0) BODY This helper makes the body of a page. It also includes a multiplication operator to increase the number of breaks. BR() CODE It performs syntax highlighting for Python, C, C&plus;&plus; and web2py code. This helper also has the ability to link an API documentation. CODE(”print “hello””, language = ”python”).xml() FIELDSET It creates an input field together with its label. FIELDSET(”Height:”, INPUT(_name = ”height”), _class = ”test”) HEAD It helps in tagging <head> tag of an HTML page. HEAD(TITLE(”<hello>”)) IMG It helps in embedding images for the given HTML page. IMG(_src = ”http://example.com/image.png”,_alt = ”test”) Custom Helpers These helpers are used to customize the tags as per the requirements. web2py uses following custom helpers − TAG web2py uses TAG as the universal tag generator. It helps in generating customized XML tags. The general syntax is as follows − {{ = TAG.name(”a”, ”b”, _c = ”d”)}} It generates the XML code as : <name c = “d”>ab</name> TAG is an object and TAG.name or TAG[”name”] is a function that returns a temporary helper class. MENU This helper makes a list of the list items or the values of the menu items, generating a tree-like structure representing the menu. The list of menu items is in the form of response.menu. For example − print MENU([[”One”, False, ”link1”], [”Two”, False, ”link2”]]) The output will be displayed as follows − <ul class = “web2py-menu web2py-menu-vertical”> <li><a href = “link1”>One</a></li> <li><a href = “link2”>Two</a></li> </ul> BEAUTIFY It helps in building representations of compound objects, including lists and dictionaries. For example, {{ = BEAUTIFY({“a”: [“hello”, XML(“world”)], “b”: (1, 2)})}} It returns an XML object serializable to XML, with a representation of its constructor argument. In this case, the representation would be − {“a”: [“hello”, XML(“world”)], “b”: (1, 2)} The output will be rendered as − <table> <tr> <td>a</td> <td>:</td> <td>hello<br />world</td> </tr> <tr> <td>b</td> <td>:</td> <td>1<br />2</td> </tr> </table> Server-side DOM Rendering Server-side rendering allows a user to pre-render the initial state of web2py components. All the derived helpers provide search element and elements to render DOM on server side. The element returns the first child element matching a specified condition. On the other hand, elements return a list of all the matching children. Both use same syntax. This can be demonstrated with the following example − a = DIV(DIV(DIV(”a”, _id = ”target”,_class = ”abc”))) d = a.elements(”div#target”) d[0][0] = ”changed” print a The output is given as − <div><div><div id = “target” class = “abc”>changed</div></div></div> Page Layout Views are used to display the output to the end users. It can extend as well as include other views as well. This will implement a tree-like structure. Example − “index.html” extends to “layout.html” which can include “menu.html” which in turn includes “header.html”. {{extend ”layout.html”}} <h1>Hello World</h1> {{include ”page.html”}} Example In the previous chapters, we created models and controllers for the company module. Now, we will focus on the creation of view, which helps in rendering the display of data. By default, the views in web2py include layout.html and index.html, which defines the overall section of displaying data. {{extend ”layout.html”}} <h2>Companies</h2> <table> {{for company in companies:}} <tr> <td>{{ = A(company.name, _href = URL(”contacts”, args = company.id))}}</td> <td>{{ = A(”edit”, _href = URL(”company_edit”, args = company.id))}}</td> </tr> {{pass}} <tr> <td>{{ =

Web2py – Useful Resources

Web2py – Useful Resources ”; Previous Next The following resources contain additional information on Web2py. Please use them to get more in-depth knowledge on this. Useful Video Courses Full Stack Web Development Course Best Seller 208 Lectures 33 hours Eduonix Learning Solutions More Detail Advanced Google Search Operators: Web Research Like the Pros 26 Lectures 1.5 hours Sasha Miller More Detail Web Application Hacking with Burp Suite 16 Lectures 2 hours Scott Cosentino More Detail Setup a Virtual Web Server using Linode or Digital Ocean 39 Lectures 2 hours YouAccel More Detail Full-Stack web app development with Angular 12, .NET Core Web API & Mongo DB Most Popular 20 Lectures 49 mins Vinay Kumar More Detail Angular 12, .NET Core Web API & Microsoft SQL Full Stack Web Development 21 Lectures 55 mins Vinay Kumar More Detail Print Page Previous Next Advertisements ”;

Web2py – Core

Web2py – Core ”; Previous Next Command Line Options We have learnt how to start the web2py server using GUI widget in the previous chapter. This widget can be skipped by starting the server from command line prompt. python web2py.py -a ”your password” -i 127.0.0.1 -p 8000 Whenever web2py server starts, it creates a file “parameters_8000.py” where all the passwords are stored in a hashed form. For additional security purpose, the following command line can be used − python web2py.py -a ”<recycle>” -i 127.0.0.1 -p 8000 For the above scenario, web2py reuses the hashed passwords stored in “parameters_8000.py“. In case, if the file “parameters_8000.py” is deleted accidently or due to some other reasons, the web-based administrative interface is disabled in web2py. URL Mapping / Dispatching The functioning of web2py is based on model-view-controller, which maps the URL in a specific form − http://127.0.0.1:8000/a/d/f.html It routes till the function “f()” mentioned in the controller d.py is under the application named “a”. If the controller is not present in the application then web2py uses a default controller named “default.py”. If the function, as given in the URL is not present, then the default function called init() is used. The working of the URL is shown schematically in the image below. The extension .html is optional for the URL. The extension determines the extension of View that renders the output of the function defined in the controller. The same content is served in multiple formats namely html, xml, json, rss etc. The request is passed, based on the functions, which accept the arguments and gives the appropriate output to the user. It is the controller, which interacts with model and view of the application for giving the output as per the user’s need. web2py – Workflow The workflow of web2py is discussed below − The web server manages each and every HTTP requests simultaneously in its own thread. The HTTP request header is parsed and passed to the dispatcher. The Dispatcher manages the application requests and maps the PATH_INFO in the URL of the function call. Every function call is represented in the URL. All the requests for files included in the static folder are managed directly, and large file are streamed to the client. Requests for anything but a static file are mapped into an action. If the request header contains a session cookie for the app, the session object is retrieved; or else, a session id is created. If the action returns a value as string, this is returned to the client. If the action returns an iterable, it is used to loop and stream the data to the client. Conditional Models In the previous chapter, we saw the functionality of the Controllers. web2py uses models, views and controllers in each of its application. Therefore, it is also necessary to understand the functionality of the Model. Unlike any other MVC application, Models in web2py are treated as conditional. Models in subfolders are executed, based on its controller’s usage. This can be demonstrated with following example − Consider the URL − http://127.0.0.1:8000/a/d/f.html In this case, ‘a’ is the name of the application, ‘d’ is the controller’s name and f() is the function associated with the controller. The list of models, which will be executed are as follows − applications/a/models/*.py applications/a/models/d/*.py applications/a/models/d/f/*.py Libraries web2py includes libraries, which are exposed to the all the applications as the objects. These objects are defined inside the core files under the directory named “gluon”. Many of the modules like DAL template have no dependencies and can be implemented outside the framework of web2py. It also maintains the unit tests which is considered as good practice. Applications web2py applications are shown below in a diagrammatic form. The Applications developed in web2py are composed of the following parts − Models − Represents data and database tables. Controllers − Describes the application logic and workflow. Views − Helps rendering the display of the data. Languages − describe how to translate strings in the application into various supported languages. Static files − Do not require processing (e.g. images, CSS style sheets etc). ABOUT and README − Details of the project. Errors − Stores error reports generated by the application. Sessions − Stores information related to each particular user. Databases − store SQLite databases and additional table information. Cache − Store cached application items. Modules − Modules are other optional Python modules. Private − Included files are accessed by the controllers but not directly by the developer. Uploads − Files are accessed by the models but not directly by the developer. API In web2py, models, controllers and views are executed in an environment where certain objects are imported for the developers. Global Objects − request, response, session, cache. Helpers − web2py includes helper class, which can be used to build HTML programmatically. It corresponds to HTML tags, termed as “HTML helpers”. For example, A, B, FIELDSET, FORM, etc. Session A session can be defined as a server-side storage of information, which is persisted throughout the user”s interaction throughout the web application. Session in web2py is the instance of storage class. For example, a variable can be stored in session as session.myvariable = “hello” This value can be retrieved as a = session.myvariable The value of the variable can be retrieved as long as the code is executed in the same session by the same user. One of the important methods in web2py for session is “forget” − session.forget(response); It instructs web2py not to save the session. Running Tasks in Background An HTTP request arrives to the web server, which handles each request in its own thread, in parallel. The task, which is active, takes place in the foreground while the others are kept in background. Managing the background tasks is also one of the main features of web2py. Time-consuming tasks are preferably kept in the background. Some of the mechanisms are listed as follows, which manage the background tasks − CRON Queues Scheduler CRON In web2py, CRON gives

Web2py – Framework Overview

Web2py – Framework Overview ”; Previous Next web2py is a full-stack web framework that can be used by a developer to completely develop a web application. It includes SQL database integration and multi-threaded web server for designing a program. Web Interface for Designing a User’s Program Once the command is executed as per the operating system, web2py displays a startup window and then displays a GUI widget that asks the user to choose − a one-time administrator password, the IP address of the network interface to be used for the web server, and a port number from which to serve requests. The administrator includes all the authority for addition and editing any new web application. By default, web2py runs its web server on 127.0.0.1:8000 (port 8000 on localhost) but a user can run it on any available IP address and port as per the requirement. The web2py GUI widget will be displayed as shown below. The password is used in the administrative interface for any changes in the new module. After the user has set the administration password, web2py starts up the web browser at the page with the following URL − http://127.0.0.1:8000/ The welcome page of the framework will be displayed as shown below. Designing a Basic Program in web2py After starting the web2py application, with the above-mentioned URL, we can use the administrative interface for creating a new module, for example, “helloWorld”. The administrative interface will ask for the password for authentication purpose as the administrator holds all the authority for addition and editing any new web application. The snapshot given above includes the page details, which lists all the installed web2py applications and allows the administrator to manage them. By default, the web2py framework comes with three applications. They are − An admin application, which the user is implementing currently. An examples application, with the online interactive documentation and an instance of the web2py official website. A welcome application. It includes the basic template for any other web2py application. It is also known as the scaffolding application. The application also welcomes a user at the startup. Let the name of the new application be “helloWorld”. Once, a new application is created, the user is redirected to a page comprising of view, model and controllers of the respective application. The user can look at the newly created application by mentioning the following URL − http://127.0.0.1:8000/helloWorld By default, a user can view the following screen on hitting the above-mentioned URL. For printing the message of the given web application “helloWorld”, the change is made in the default.py controller. The function named “index” is the default function for returning the value and displaying the necessary output. As mentioned above, the string “Hello World- Welcome to my first web application” is used as the return value, which displays the output in the screen. The output is displayed as follows − Postbacks The mechanism of validating the input of form is very common and is not considered as such a good programming practice. The input is validated each time, which is a burden for validation. A better pattern in web2py is to submit forms to the same action, which generates them. This mechanism is called as “postback” which is the main feature of web2py. In short, self-submission is achieved in postback. def first(): if request.vars.visitor_name: #if visitor name exists session.visitor_name = request.vars.visitor_name redirect(URL(”second”))#postback is implemented return dict() CRUD Application web2py includes applications, which perform the functions of Create, retrieve, update and delete. The CRUD cycle describes the elemental functions of a database, which is persistent. All the application logic is written in the models, which are retrieved by the controllers and displayed to the users with the help of view. appadmin For PHP, the application server includes listing of all the databases under phpmyadmin. In a similar way, web2py provides an interface for managing, creating and deleting tables or databases, which is termed as “appadmin.” Before implementing the logic behind the tables, it is necessary to create database and its associated tables. The URL to access appadmin − http://127.0.0.1:8000/applicationname/appadmin On hitting the URL, the user will get the list of tables associated for the given application. This interface is not intended to be public. It is designed to get an easy access to the database. It consists of two files namely − a controller “appadmin.py” and a view “appadmin.html”. It can paginate up to 100 records at a time. The usage of “appadmin” is discussed in subsequent chapters. Print Page Previous Next Advertisements ”;

Web2py – Python Language

Web2py – Python Language ”; Previous Next Python can be defined as a combination of object-oriented and interactive language. It is an open source software. Guido van Rossum conceived python in the late 1980s. Python is a language similar to PERL (Practical Extraction and Reporting Language), which has gained popularity because of its clear syntax and readability. The main notable features of Python are as follows − Python is said to be relatively easy to learn and portable. Its statements can be easily interpreted in a number of operating systems, including UNIX-based systems, Mac OS, MS-DOS, OS/2, and various versions of Windows. Python is portable with all the major operating systems. It uses an easy to understand syntax, making the programs, which are user friendly. It comes with a large standard library that supports many tasks. From the above diagram, it is clearly visible that Python is a combination of scripting as well as programming language. They are interpreted within another program like scripting languages. Versions of Python Python has three production-quality implementations, which are called as CPython, Jython, and IronPython. These are also termed as versions of Python. Classic Python a.k.a CPython is a compiler, interpreter and consists of built-in and optional extension modules which is implemented in standard C language. Jython is a Python implementation for Java Virtual Machine (JVM). IronPython is designed by Microsoft, which includes Common Language Runtime (CLR). It is commonly known as .NET Starting Up A basic Python program in any operating system starts with a header. The programs are stored with .py extension and Python command is used for running the programs. For example, python_rstprogram.py will give you the required output. It will also generate errors, if present. Python uses indentation to delimit blocks of code. A block starts with a line ending with colon, and continues for all lines in the similar fashion that have a similar or higher indentation as the next line. # Basic program in Python print “Welcome to Python!n” The output of the program will be − Welcome to Python! Indentation Indentations of the programs are quite important in Python. There are some prejudices and myths about Python”s indentation rules for the developers who are beginners to Python. The thumb rule for all the programmers is − “Whitespace is significant in Python source code.” Leading whitespace, which includes spaces and tabs at the beginning of a logical line of Python computes the indentation level of line. Note The indentation level also determines the grouping of the statements. It is common to use four spaces i.e. tab for each level of indentation. It is a good policy not to mix tabs with spaces, which can result in confusion, which is invisible. Python also generates a compile time error if there is lack of indentation. IndentationError: expected an indented block Control Flow Statements The control flow of a Python program is regulated by conditional statements, loops and function calls. The If statement, executes a block of code under specified condition, along with else and elif(a combination of else-if). The For statement, iterates over an object, capturing each element to a local variable for use by the attached block. The While statement, executes a block of code under the condition, which is True. The With statement, encloses a code block within the context manager. It has been added as a more readable alternative to the try/finally statement. # If statement in Python x = int(raw_input(“Please enter an integer: “)) #Taking input from the user if x<0: print “1 – Got a negative expression value” print x else: print “1 – Got a positive expression value” print x print “Good bye!” Output sh-4.3$ python main.py Please enter an integer: 4 1 – Got a positive expression value 4 Good bye! Functions The statements in a typical Python program are organized and grouped in a particular format called, “Functions”. A function is a group of statements that perform an action based on the request. Python provides many built-in functions and allows programmers to define their own functions. In Python, functions are values that are handled like other objects in programming languages. The def statement is the most common way to define a function. def is a single-clause compound statement with the following syntax − def function-name (parameters):statement(s) The following example demonstrates a generator function. It can be used as an iterable object, which creates its objects in a similar way. def demo (): for i in range(5): yield (i*i) for j in demo(): print j Output sh-4.3$ python main.py 0 1 4 9 16 Special Attributes, Methods, and Operators The attributes, methods, and operators starting with double underscore of a class are usually private in behavior. Some of them are reserved keywords, which include a special meaning. Three of them are listed below − __len__ __getitem__ __setitem__ The other special operators include __getattr__ and __setattr__, which defines the get and set attributes for the class. File I/O Functions Python includes a functionality to open and close particular files. This can be achieved with the help of open(), write() and close() functions. The commands which help in file input and output are as follows − Sr.No Command & Functionality 1 open() It helps in opening a file or document 2 write() It helps to write a string in file or document 3 read() It helps in reading the content in existing file 4 close() This method closes the file object. Example Consider a file named “demo.txt”, which already exists with a text “This is a demo file”. #!/usr/bin/python # Open a file fo = open(“demo.txt”, “wb”) fo.write( “Insering new line n”); # Close opend file fo.close() The string available after opening the file will be − This is a demo file Inserting a new line Print Page Previous Next Advertisements ”;

Web2py – Home

Web2py Tutorial PDF Version Quick Guide Resources Job Search Discussion web2py is defined as a free, open-source web framework for agile development which involves database-driven web applications. It is written and programmable in Python. It is a full-stack framework and consists of all the necessary components a developer needs to build fully functional web applications. Audience This tutorial is primarily meant for software professionals who work on Python and are required to create scalable, secure and portable database-driven web-based applications. web2py provides all the functionalities to create, modify, deploy, and manage an application from anywhere using your browser. Prerequisites Before you start proceeding with this tutorial, we are assuming that you are already aware of the basics of Python programming. A basic understanding of Model-View-Controller is also equally important. If you are not well aware of these concepts, then we will suggest you to go through our short tutorial on Python. Print Page Previous Next Advertisements ”;

Web2py – Introduction

Web2py – Introduction ”; Previous Next web2py is defined as a free, open-source web framework for agile development which involves database-driven web applications; it is written in Python and programmable in Python. It is a full-stack framework; it consists of all the necessary components, a developer needs to build a fully functional web application. web2py framework follows the Model-View-Controller pattern of running web applications unlike traditional patterns. Model is a part of the application that includes logic for the data. The objects in model are used for retrieving and storing the data from the database. View is a part of the application, which helps in rendering the display of data to end users. The display of data is fetched from Model. Controller is a part of the application, which handles user interaction. Controllers can read data from a view, control user input, and send input data to the specific model. web2py has an in-built feature to manage cookies and sessions. After committing a transaction (in terms of SQL), the session is also stored simultaneously. web2py has the capacity of running the tasks in scheduled intervals after the completion of certain actions. This can be achieved with CRON. web2py – Workflow Take a look at the workflow diagram given below. The workflow diagram is described below. The Models, Views and Controller components make up the user web2py application. Multiple applications can be hosted in the same instance of web2py. The browser sends the HTTP request to the server and the server interacts with Model, Controller and View to fetch the necessary output. The arrows represent communication with the database engine(s). The database queries can be written in raw SQL or by using the web2py Database Abstraction Layer (which will be discussed in further chapters), so that web2py application code is independent of any database engine. Model establishes the database connection with the database and interacts with the Controller. The Controller on the other hand interacts with the View to render the display of data. The Dispatcher maps the requested URL as given in HTTP response to a function call in the controller. The output of the function can be a string or a hash table. The data is rendered by the View. If the user requests an HTML page (the default), the data is rendered into an HTML page. If the user requests the same page in XML, web2py tries to find a view that can render the dictionary in XML. The supported protocols of web2py include HTML, XML, JSON, RSS, CSV, and RTF. Model-View-Controller The model-view-controller representation of web2py is as follows − Model “db.py” is the model: db = DAL(”sqlite://storage.sqlite”) db.define_table(employee, Field(”name”), Field(‘phone’)) The Model includes the logic of application data. It connects to the database as mentioned in the figure above. Consider SQLite is being used and is stored in storage.sqlite file with a table defined as employee. If the table does not exist, web2py helps by creating the respective table. Controller The program “default.py” is the Controller. def employees(): grid = SQLFORM.grid(db.contact, user_signature = False) return locals() In web2py, URL mapping helps in accessing the functions and modules. For the above example, the Controller contains a single function (or “action”) called employees. The action taken by the Controller returns a string or a Python dictionary, which is a combination of key and value including a local set of variables. View “default/contacts.html” is the View. {{extend ”layout.html”}} <h1>Manage My Employees</h1> {{=grid}} For the given example, View displays the output after the associated controller function is executed. The purpose of this View is to render the variables in the dictionary, which is in the form of HTML. The View file is written in HTML, but it embeds Python code with the help of {{ and }} delimiters. The code embedded into HTML consists of Python code in the dictionary. Start with web2py web2py comes in binary packages for all the major operating systems like Windows, UNIX and Mac OS X. It is easy to install web2py because − It comprises of the Python interpreter, so you do not need to have it pre-installed. There is also a source code version that runs on all the operating systems. The following link comprises of the binary packages of web2py for download as per the user’s need − www.web2py.com The web2py framework requires no pre-installation unlike other frameworks. The user needs to download the zip file and unzip as per the operating system requirement. The web2py framework is written in Python, which is a complete dynamic language that does not require any compilation or complicated installation to run. It uses a virtual machine like other programming languages such as Java or .net and it can transparently byte-compile the source code written by the developers. Operating System Command Unix and Linux (source distribution) python web2py.py OS X (binary distribution) open web2py.app Windows (binary web2py distribution) web2py.exe Windows (source web2py distribution) c:/Python27/python.exe web2py.py Print Page Previous Next Advertisements ”;

Web2py – Quick Guide

Web2py – Quick Guide ”; Previous Next Web2py – Introduction web2py is defined as a free, open-source web framework for agile development which involves database-driven web applications; it is written in Python and programmable in Python. It is a full-stack framework; it consists of all the necessary components, a developer needs to build a fully functional web application. web2py framework follows the Model-View-Controller pattern of running web applications unlike traditional patterns. Model is a part of the application that includes logic for the data. The objects in model are used for retrieving and storing the data from the database. View is a part of the application, which helps in rendering the display of data to end users. The display of data is fetched from Model. Controller is a part of the application, which handles user interaction. Controllers can read data from a view, control user input, and send input data to the specific model. web2py has an in-built feature to manage cookies and sessions. After committing a transaction (in terms of SQL), the session is also stored simultaneously. web2py has the capacity of running the tasks in scheduled intervals after the completion of certain actions. This can be achieved with CRON. web2py – Workflow Take a look at the workflow diagram given below. The workflow diagram is described below. The Models, Views and Controller components make up the user web2py application. Multiple applications can be hosted in the same instance of web2py. The browser sends the HTTP request to the server and the server interacts with Model, Controller and View to fetch the necessary output. The arrows represent communication with the database engine(s). The database queries can be written in raw SQL or by using the web2py Database Abstraction Layer (which will be discussed in further chapters), so that web2py application code is independent of any database engine. Model establishes the database connection with the database and interacts with the Controller. The Controller on the other hand interacts with the View to render the display of data. The Dispatcher maps the requested URL as given in HTTP response to a function call in the controller. The output of the function can be a string or a hash table. The data is rendered by the View. If the user requests an HTML page (the default), the data is rendered into an HTML page. If the user requests the same page in XML, web2py tries to find a view that can render the dictionary in XML. The supported protocols of web2py include HTML, XML, JSON, RSS, CSV, and RTF. Model-View-Controller The model-view-controller representation of web2py is as follows − Model “db.py” is the model: db = DAL(”sqlite://storage.sqlite”) db.define_table(employee, Field(”name”), Field(‘phone’)) The Model includes the logic of application data. It connects to the database as mentioned in the figure above. Consider SQLite is being used and is stored in storage.sqlite file with a table defined as employee. If the table does not exist, web2py helps by creating the respective table. Controller The program “default.py” is the Controller. def employees(): grid = SQLFORM.grid(db.contact, user_signature = False) return locals() In web2py, URL mapping helps in accessing the functions and modules. For the above example, the Controller contains a single function (or “action”) called employees. The action taken by the Controller returns a string or a Python dictionary, which is a combination of key and value including a local set of variables. View “default/contacts.html” is the View. {{extend ”layout.html”}} <h1>Manage My Employees</h1> {{=grid}} For the given example, View displays the output after the associated controller function is executed. The purpose of this View is to render the variables in the dictionary, which is in the form of HTML. The View file is written in HTML, but it embeds Python code with the help of {{ and }} delimiters. The code embedded into HTML consists of Python code in the dictionary. Start with web2py web2py comes in binary packages for all the major operating systems like Windows, UNIX and Mac OS X. It is easy to install web2py because − It comprises of the Python interpreter, so you do not need to have it pre-installed. There is also a source code version that runs on all the operating systems. The following link comprises of the binary packages of web2py for download as per the user’s need − www.web2py.com The web2py framework requires no pre-installation unlike other frameworks. The user needs to download the zip file and unzip as per the operating system requirement. The web2py framework is written in Python, which is a complete dynamic language that does not require any compilation or complicated installation to run. It uses a virtual machine like other programming languages such as Java or .net and it can transparently byte-compile the source code written by the developers. Operating System Command Unix and Linux (source distribution) python web2py.py OS X (binary distribution) open web2py.app Windows (binary web2py distribution) web2py.exe Windows (source web2py distribution) c:/Python27/python.exe web2py.py Web2py – Python Language Python can be defined as a combination of object-oriented and interactive language. It is an open source software. Guido van Rossum conceived python in the late 1980s. Python is a language similar to PERL (Practical Extraction and Reporting Language), which has gained popularity because of its clear syntax and readability. The main notable features of Python are as follows − Python is said to be relatively easy to learn and portable. Its statements can be easily interpreted in a number of operating systems, including UNIX-based systems, Mac OS, MS-DOS, OS/2, and various versions of Windows. Python is portable with all the major operating systems. It uses an easy to understand syntax, making the programs, which are user friendly. It comes with a large standard library that supports many tasks. From the above diagram, it is clearly visible that Python is a combination of scripting as well as programming language. They are interpreted within another program like scripting languages. Versions of Python Python has three production-quality implementations, which are called