Thursday, January 22, 2015

web2py + Apache + wsgi(Uniform Server) failed for the latest 2.9.12

It has been a long time since I setup the web2py server and they are still running 2.4.6. I decided to refresh my memory and version up!

....


Then I'm failed.

See the forum below.
https://groups.google.com/forum/#!topic/web2py/yBM8Ybl_xGA


It sounds like the latest web2py 2.9.12 doesn't work with apache using wsgi.

I already posted a ticket here.
https://code.google.com/p/web2py/issues/detail?id=2036

If your server configuration is something similar to me, I recommend wait until this ticket is fixed!

Thursday, May 9, 2013

web2py Dynamically change highlighted class for response.menu

I'm trying to add simple function to my website but didn't know what to do. Niphlod provided me the snippet in web2py forum so I can share it here!

1. Create new app called "highlight"

2. Overwrite the response.menu in menu.py


response.menu = [
    (SPAN('Home', _id='default_highlighted'), False, URL('default', 'index'), []),
    (SPAN('Menu1'), False, URL('default', 'menu1'), []),
    (SPAN('Menu2'), False, URL('default', 'menu2'), [])
]

3. add the following script right before </head> in layout.html



<script>
jQuery(function() {
  var path = location.pathname.substring(1);
    if ( path ) {
        var els = jQuery('ul.nav a[href$="'+path+'"]').filter("[rel!=nofollow]");
        if (els.length != 0) {

            els.find('span').addClass('highlighted');
        } else {
            jQuery('#default_highlighted').find('span').addClass('highlighted');
        }
    }
})
</script>


4. Create empty action in controllers/default.py for test purpose


def index():
    return dict('')

def menu1():
    return dict('')

def menu2():
    return dict('')

5. And empty views default/menu1.html and default/menu2.html

6. TA-DA








Wednesday, February 27, 2013

web2py jquery mobile plugin

So this year I'm trying to work on mobile development. I realized it's hard for me to learn all the language for the native app for each platform (apple, android, blackberry...etc) and found jQuery Mobile. It's so cool how come I didn't know about it!

I finished reading the book and What?? web2py already has the plugin !! OMG, I love web2py.

You can download it from here.
http://web2py.com/plugins/plugin_jqmobile/about

Thank you, Jason, Timothy, Harkirat and Massimo.


As of today, there is a issue and you will get blank page when you install the plugin.
I already submit a ticket (#1354: jQuery Mobile Plugin layout issue) with the solution.


Yeah! It looks great !!


Tuesday, October 23, 2012

web2py grid with export dropdown

I just want to share the code that Paolo Caruccio created to show the export dropdown for grid instead of links. It looks very clean and this should be the default for grid layout!

web2py forum link
https://groups.google.com/forum/?fromgroups=#!topic/web2py/HsFWsQmGONM

To test, create new app and add/edit as follows.

Model

db.define_table('Category',
    Field('Code', 'integer'),
    Field('Name'),
    format='%(Name)s')

Controller

def index():
    query = db.Category.id >0
    grid = SQLFORM.grid(query,csv=True,paginate=10)
    return dict(grid=grid)

View


{{extend 'layout.html'}}
{{
if not request.args:

 w2p_grid_tbl = grid.element('table')
 if w2p_grid_tbl:
 original_export_menu = grid.element('div.w2p_export_menu')
 export_menu_links = original_export_menu.elements('a')
 export_menu_items = []
 for link in export_menu_links:
 item = LI(link)
 export_menu_items.append(item)
 pass
 new_export_menu = DIV(
                      A( T('Exports'),
                         SPAN(_class='caret'),
                         _href='#',
                         _class='btn dropdown-toggle',
                         **{'_data-toggle':"dropdown"}
                        ),
                      UL(*export_menu_items,
                         _class='dropdown-menu'
                        ),
                    _class='w2p_export_menu btn-group'
                    )
 export_menu = grid.element('div.w2p_export_menu',replace=new_export_menu)
 pass
pass
}}
{{=grid}}


Before
After




Monday, July 2, 2012

web2py slices: cascading drop down lists with ajax 2

New web2py slice post ! I'm happy because it works perfectly now !!

cascading drop down lists with ajax 2
http://www.web2pyslices.com/slice/show/1526/cascading-drop-down-lists-with-ajax-2

Why it's 2?
because this is improved version of my previous slice.

You can check the working sample on my pythonanywhere site.
http://ochiba.pythonanywhere.com/dropdown/default/index



Monday, June 18, 2012

How to use gmaps.js on web2py

It's easy to handle Google Maps on your website and of course it will be much easier if you use web2py!

1. Create new app called gmap


2. Download gmaps.js
Go to http://hpneo.github.com/gmaps/ and download gmaps.js. Place it under the app folder static/js/gmaps.js

3. controllers/default.py
Replace the def index() with the following.

def index():
    from gluon.tools import geocode
    latitude = longtitude = ''
    form=SQLFORM.factory(Field('search'), _class='form-search')
    form.custom.widget.search['_class'] = 'input-long search-query'
    form.custom.submit['_value'] = 'Search'
    form.custom.submit['_class'] = 'btn'
    if form.accepts(request):
        address=form.vars.search
        (latitude, longitude) = geocode(address)
    else:
        (latitude, longitude) = ('','')
    return dict(form=form, latitude=latitude, longitude=longitude)
Note:  There was an issue #855 and just fixed with the Version 2.0.0 (2012-06-17 23:36:32) dev. If you are using the web2py version older than this, make sure to replace the latitude and longitude as follows.
 (longitude, latitude) = geocode(address)
4. views/default/index.html
Replace it with the following.

{{extend 'layout.html'}}
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script src="{{=URL('static','js/gmaps.js')}}"></script>
<div>
{{=form.custom.begin}}
{{=form.custom.widget.search}}{{=form.custom.submit}}
{{=form.custom.end}}
</div>
{{if longitude or latitude:}}
<p>latitude, longtitude: {{=latitude}},{{=longitude}}</p>
<div id="map" style="height:400px;width:800px"></div>
<script>
$(document).ready(function(){
  map = new GMaps({
    div: '#map',
    lat: {{=latitude}},
    lng: {{=longitude}}
  });
   map.addMarker({
    lat: {{=latitude}},
    lng: {{=longitude}},
    title: 'Here!',
    infoWindow: {
        content: '<p>{{=request.vars.search}}</p>'
    }
  });
});
</script>
{{pass}}
5. Result
Type "243 S Wabash Ave, Chicago, IL, USA" and see the result.




Friday, June 8, 2012

web2py on PythonAnywhere

It's too bad fluxflex will shut down and will be no longer available on June 30, 2012. It was great service, easy to deploy, I was a little bit frustrated with using git but overall I enjoyed. Especially, I was one of the fun because this company was established by young Japanese guys !

I was looking for new place and introduced PythonAnywhere in the web2py forum.

It's so easy to install. All you have to do is sign up for free account, click web2py icon and Done !
I was running my test app in a few minutes.

Wow! I'm very impressed!!


Maybe I can spend $9 per month to host it under own domain name. The performance should be enough  for the small app !

I'm not familiar with console (I'm windows guy) so I wonder how I can update wen2py when new version is available...


Thursday, May 24, 2012

web2py slices: Import CSV file with user information and date

Posted new slice Import CSV file with user information and date

Sometime it's critical to keep tracking who updated the records. Built-in CSV import function is great but doesn't update the field such as updated_on, updated_by fields. Here's how I solved the problem.

1. Sample application image


2. Result




Wednesday, May 2, 2012

web2py bootstrap in trunk

I'm very excited about bootstrap which is now available in trunk.

This is my web2py app with bootstrap layout. It's really clean and attractive. Now I don't have to worry about layout design which I'm not really good at.

By default, some of css is conflicting with existing web2py.css, so I made the following change to make it more like bootstrap.

In web2py.css, comment out from #2 - #5, #16 - #37 and #100.


You can find more about bootstrap here.

Thursday, March 15, 2012

web2py app runs very slow via VPN (SOLVED)

My application works super fast when I connected in LAN but it takes about 60 sec every time the page is refreshed via VPN. This is so strange....



After a few hours of investigation, I found in the layout.html, it's trying to connect js and css files on the internet which is impossible to connect via VPN ! So my app keeps trying to connect the files over and over about 60 sec and finally gave up.

Version 1.99.4 (By default, it was NOT commented out)


    <!-- uncomment here to load jquery-ui -->
   
    <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css" type="text/css" media="all" />
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js" type="text/javascript"></script>
   
   <!-- uncomment to load jquery-ui -->


Versioon 1.99.4 (By default, it's commented out !! Yeah !)


 <!-- uncomment here to load jquery-ui
  <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css" type="text/css" media="all" />
  <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js" type="text/javascript"></script>
  uncomment to load jquery-ui //-->

TIPS for VPN
If you want to use the js and css files and your app may be connected by VPN, you should download the files and placed to local such as under "static/js" and "static/css".

Monday, February 13, 2012

Calling remote program on DB2 from Python/Web2py

I never realized the power of stored procedure on DB2 and now I can execute the CL/RPG/QRY program from python/web2py !


1. Create Stored Procedure

Let's say, I have a CL program called MYCLPGM in MYLIB. In CL program, I added libraries, clear files and call RPG program..etc.

Then, I can create stored procedures called MYPRCD as follows.
STRSQL 
CREATE PROCEDURE MYLIB/MYPRCD LANGUAGE CL NOT DETERMINISTIC
CONTAINS SQL EXTERNAL NAME MYLIB/MYCLPGM PARAMETER STYLE  
GENERAL



You can also set up parameters or select different language if you need. I recommend using CL and call whatever you need from there because most of case, your objects are in different libraries and you can add them in CL.


After it's created, you can check the stored procedures information in here
STRSQL 
VIEW ROUTINE
SELECT * FROM SYSROUTINES WHERE SPECIFIC_NAME ='MYPRCD'

VIEW PARAMETERS
SELECT * FROM SYSPARMS


From DB2, you can call the stored procedure like
STRSQL 
CALL MYLIB/MYPRCD

2. Calling from Python
* I assume you already finished my previous post.


>>> import pyodbc
>>> conn = pyodbc.connect('DSN=MYDSN;UID=xxxxx;PWD=xxxxx')
>>> cursor = conn.cursor()
>>> cursor.execute('CALL MYLIB.MYPRCD')
<pyodbc.Cursor object at 0x01E7DA30>
>>> conn.close
>>> conn.close() 
3. Calling from web2py (Tested with Ver 1.99.4)
* I assume you already finished my previous post.

Yes, you can do it using executesql.

Model
-------------------------------------------------------------------
db = DAL('db2://DSN=MYDSN;UID=xxxxx;PWD=xxxxx', migrate_enabled=False)
-------------------------------------------------------------------

Controller
-------------------------------------------------------------------
def index():
    form=SQLFORM.factory()
    if form.accepts(request):
        db.executesql('CALL MYLIB.MYPRCD')
        response.flash = 'Stored Executed !!'
    return dict(form=form)
-------------------------------------------------------------------

View
-------------------------------------------------------------------
{{extend 'layout.html'}}

<h3>Run stored procedure</h3>
<hr>
{{=form}}
-------------------------------------------------------------------





Friday, January 13, 2012

web2py: plugin rating widget

I was looking for a plugin for rating with starts and found this one but it doesn't give me much information how to do it so I gave up. (It's sad, I couldn't plug the plugin.)

Plugin Rating
http://www.web2py.com/plugins/default/rating

Now, kenji (s-cubism) just introduced the new plugin and it works like a charm ! It's easy to use and I strongly recommend if you're looking for the plugin.

Rating Widget
http://dev.s-cubism.com/plugin_rating_widget 

Here's how I did.

1. Create new app called "rating"

2. Create models/rating.py
# coding: utf8
from plugin_rating_widget import RatingWidget
db.define_table('product',
    Field('rating', 'integer',
          requires=IS_IN_SET(range(1,6)), # "requires" is necessary for the rating widget
))
################################ The core ######################################
# Inject the horizontal radio widget
db.product.rating.widget = RatingWidget()
################################################################################

3.  Edit controllers/default.py for def index

def index():
    form = SQLFORM(db.product)
    if form.accepts(request.vars, session):
        session.flash = 'submitted %s' % form.vars
        redirect(URL('index'))
    return dict(form=form)
4. Edit views/default.html

{{left_sidebar_enabled,right_sidebar_enabled=False,True}}
{{extend 'layout.html'}}
{{=form}}
5. Result

Of course, you can create another table and store the submitted value to it, calculate the average, whatever you like. This plugin is good enough for me to build some kind of user review app !




Tuesday, December 27, 2011

web2py: new appliances web site

Oh, my app I developed for final project for Massimo's class is now available on new appliances site.

Restaurants Listing

Tuesday, December 20, 2011

web2py: social gathering in Chicago


We had a social gathering at Exchequer Restaurant & Pub which is very close to DePaul Unitversity.


http://www.exchequerpub.com/

226 S. Wabash Avenue
Chicago, IL 60604
Phone: (312) 939-5633

It was fun meeting with the small local group and let's do it again !
I missed the train at 9:40, waited until 10:40 then got home almost 12:00... feel so sleepy today.






Monday, November 21, 2011

web2py: hide register link on page

The following code will hide the link but also disable the function to register user completely even you create the record from appadmin menu.

auth.settings.actions_disabled=['register']

So here's how I do...

# all we need is login
auth.settings.actions_disabled=['change_password','request_reset_password','retrieve_username','profile']
if request.controller != 'appadmin':
    auth.settings.actions_disabled +=['register']

In this way, it's disabled for users but not admin.

web2py: add additonal field in auth_user

It's actually very easy. Just add the following code in your model before auth.define_tables().



## additonal fields
auth.settings.extra_fields['auth_user']= [
  Field('office')
  ]

So it will be like this...

from gluon.tools import Auth, Crud, Service, PluginManager, prettydate
auth = Auth(db, hmac_key=Auth.get_or_create_key())
crud, service, plugins = Crud(db), Service(), PluginManager()

## create all tables needed by auth if not custom tables
## additonal fields
auth.settings.extra_fields['auth_user']= [
  Field('office')
  ]
auth.define_tables()

Wednesday, October 19, 2011

web2py: how to connect existing tables


Tested environment:
mssql 2008

DAL
You need to make sure you disable Migration otherwise it might alter your tables. I recommend to specify at connection level (not each table) so that you don't forget.

db = DAL("mssql2://YourID:YourPassword@YourServer/YourDB", migrate=False)

If table has Primary field called id
You're lucky. This meet with the convention of web2py


You can connect with the following.
db.define_table('table1',
    Field('name'))
If table has primary key field called ID
Shoot, it's a capital letter... don't worry the code above will still work !

If table has primary key field called myid
Why didn't I name the field carefully.... no problem. You can still connect.
Since it's not field called id/ID, you need to define your primary field just like others and set primarykey for it.
db.define_table('table1',
    Field('myid'),
    Field('name'),
    primarykey=['myid'])
If table has No primary key field
What's wrong with me ? ... don't worry here's what I found. You know what, the above code still works !





Friday, October 14, 2011

How to set up web2py + ldap with Windows Active Directory

This is a recipe to use web2py + ldap in the real world.

Install python-ldap
1. Download and install  python-ldap (e.g. python-ldap-2.4.3.win32-py2.7)

Edit models/db.py
2. edit auth.define_tables() to allow login with username and not email.


auth.define_tables(username=True)

3. Add the following at the bottom of page.
Replace server and base_dn to your setting.

# all we need is login
auth.settings.actions_disabled=['register','change_password','request_reset_password','retrieve_username','profile']

# you don't have to remember me
auth.settings.remember_me_form = False

# ldap authentication and not save password on web2py
from gluon.contrib.login_methods.ldap_auth import ldap_auth
auth.settings.login_methods = [ldap_auth(mode='ad',
   server='OchibaServer',
   base_dn='dc=ochiba,dc=com')]

4. Result










Wednesday, October 12, 2011

How to setup web2py + Apache + wsgi (Uniform Server)

The problem for pyodbc in my previous post will be avoided if you use Uniform Server which comes with Apache, mysql, php. Uniform server is very simple and portable (You can even run from USB memory) so I decided to use this until the Apache problem is solved on the next Win32 Binary.

The original instruction was provided by Paolo Caruccio at web2py-users forum.


Pre-Requirement:
Finished my previous post

Install Uniform Server
1. Download and install Uniform Server (Orion_7_1_11.exe)

2. Run Orion_7_1_11.exe, and Extract to: "C:\". This will create C:\UniServer folder.

3. Run C:\UniServer\Start.exe. You can access Uniform Server from System Tray.



4. Click Start UniServer (Apache MySQL).

Server certificate for https
5. If you have, place under  the following

C:\UniServer\usr\local\apache2\conf\ssl.crt\server.crt
C:\UniServer\usr\local\apache2\conf\ssl.key\server.key

Or

From Uniform Server menu, go to Advanced - Server Certificate and key generator and follow the wizard. It will create the files automatically.


mod_wsgi
6. Download from mod_wsgi-win32-app22py27-3.3.so (This is for Python 2.7.x), renamed and place to C:\UniServer\usr\local\apache2\modules\mod_wsgi.so

Edit httpd.conf
7. Back up and open C:\UniServer\usr\local\apache2\conf\httpd.conf

7.1 Add mod_wsgi after all the other LoadModule lines

LoadModule vhost_alias_module modules/mod_vhost_alias.so
LoadModule wsgi_module modules/mod_wsgi.so

7.2 Add the following at the end of file and save

Include conf/vhost_web2py.conf

7.3 Create C:\UniServer\usr\local\apache2\conf\vhost_web2py.conf and put the following lines (Change ServerName, ServerAdmin to yours) and save.


##########VIRTUAL HOST SETUP##########
# WEB2PY.LOCALHOST
<VirtualHost *:80>
ServerName ochiba-183
DocumentRoot C:/web2py/applications
WSGIScriptAlias / "C:/web2py/wsgihandler.py"
ServerAdmin admin@abc.com
<LocationMatch "^(/[\w_]*/static/.*)">
Order Allow,Deny
Allow from all
</LocationMatch>
<Location "/">
Order deny,allow
Allow from all
</Location>
LogFormat "%h %l %u %t \"%r\" %>s %b" common
LogLevel notice
CustomLog C:/UniServer/tmp/web2py.access.log common
ErrorLog C:/UniServer/tmp/web2py.error.log
</VirtualHost>
#------------------------------------------------------------
<VirtualHost *:443>
ServerName ochiba-183
ServerAdmin admin@abc.com
DocumentRoot C:/web2py/applications
WSGIScriptAlias / "C:/web2py/wsgihandler.py"
<LocationMatch "^(/[\w_]*/static/.*)">
Order Allow,Deny
Allow from all
</LocationMatch>
<Location "/">
Order deny,allow
Allow from all
</Location>
<Directory "C:/web2py">
Order allow,deny
Deny from all
</Directory>
LogFormat "%h %l %u %t \"%r\" %>s %b" common
LogLevel notice
CustomLog C:/UniServer/tmp/web2py.access.log common
ErrorLog C:/UniServer/tmp/web2py.error.log
SSLEngine on
SSLProtocol -all +TLSv1 +SSLv3
SSLCipherSuite HIGH:MEDIUM:!aNULL:+SHA1:+MD5:+HIGH:+MEDIUM
SSLCertificateFile C:/UniServer/usr/local/apache2/conf/ssl.crt/server.crt
SSLCertificateKeyFile C:/UniServer/usr/local/apache2/conf/ssl.key/server.key
SetEnvIf User-Agent ".*MSIE.*" \
</VirtualHost>
##########END VIRTUAL HOST SETUP##########



7.4 From Uniform Server menu, Stop UniServer  (Apache MySQL) and Start.

7.5 Go to http://(Your Server Name) or https://(Your Server Name)

In my case, http://ochiba-183

7.6  you will see web2py welcome screen !!