Differences between revisions 11 and 12
Revision 11 as of 2009-08-04 15:36:23
Size: 7039
Comment:
Revision 12 as of 2009-08-31 21:19:21
Size: 7370
Comment:
Deletions are marked like this. Additions are marked like this.
Line 179: Line 179:
== Serving files and its mime type ==

{{{
If

"""
   @expose(content_type=CUSTOM_CONTENT_TYPE)
   def image(self, id):
         image = Image.get(id)
         pylons.request['Content-Type'] = image.mime_type
         return image.data
"""

So, instead of "image.mime_type", "mimetyes.guess_type(filename)[0]".

}}}

FAQ

Not directly via config, no.

Your post pointed me in the right direction. I tried your idea, but
the SessionMiddleware is needed (they call it core middleware  for a
reason). Other code expects it to be there, so it can't be just
removed. Instead, I went one level deeper and modified the
SessionMiddleware itself to NOT set a cookie. I didn't want to modify
the beaker package itself of course (bad practice). I could in theory
subclass the beaker SessionMiddleware and then sublass AppConfig to
add my custom SessionMiddleware, but it becomes a little cumbersome.
So, I ended up just replacing the __call__the method of the original
beaker SessionMiddleware in my AppCfg.py file. The commented lines
bellow are the lines that set the cookie:


### Start code #####
from beaker.middleware import SessionMiddleware
from beaker.session import SessionObject
def custom_session_middleware__call__(self, environ, start_response):
   session = SessionObject(environ, **self.options)
   if environ.get('paste.registry'):
       if environ['paste.registry'].reglist:
           environ['paste.registry'].register(self.session, session)
   environ[self.environ_key] = session
   environ['beaker.get_session'] = self._get_session

   def session_start_response(status, headers, exc_info = None):
       #if session.accessed():
       #    session.persist()
       #    if session.__dict__['_headers']['set_cookie']:
       #        cookie = session.__dict__['_headers']['cookie_out']
       #        if cookie:
       #            headers.append(('Set-cookie', cookie))
       return start_response(status, headers, exc_info)
   return self.wrap_app(environ, session_start_response)

SessionMiddleware.__call__ = custom_session_middleware__call__
### End code #####

mounting test-controllers/getting root-controller instance

Assuming the paster-stuff is bootstrapped through code like

  here_dir = os.path.dirname(os.path.abspath(ableton.__file__))
  conf_dir = os.path.dirname(here_dir)
  wsgiapp = loadapp('config:test.ini', relative_to=conf_dir)

you then can do it simply like this (inside a function/method!!)

  import myproject.controllers.root as root
  root.RootController.mountpoint = TestController()

Then you can access the controller through the usual

  self.app.get("/mountpoint/action")

Of course mounting of whole controller hierarchies is perfectly fine.

So I create a function in our base-test-class that allows to register a passed
controller for a given mountpoint. Voila, greatness ensues.

retrieve user identity

  • You can get the current logged in identity by grabbing it from the

environ:

identity = request.environ.get('repoze.who.identity')
user = identity.user
group_names = identity.groups
  • Lots of folks do something like this in their call method of their

BaseController:

tmpl_context.identity = request.environ.get('repoze.who.identity')
  • In your template you could do the following:

    <li py:if="tg.predicates.has_permission('can_manage_links')"><a href="${tg.url('/links/')}">Postal Links Mgmt</a></li>
    <li py:if="tg.predicates.has_any_permission('can_create_events', 'can_edit_events', 'can_delete_events')">
    <a href="${tg.url('/events/')}">Events Mgmt</a></li>
    <li py:if="tg.predicates.has_permission('can_see_ban_reason')"><a href="${tg.url('/usermgt/')}">User Mgmt</a></li>
  • OR

<span py:if="tg.predicates.in_group('banned')">

login_handler and userid

Problem:

I am trying to implement post logon url so that the user is directed
to an appropriate page after they log in.  How do I specify which page
the user will get directed to based on their username and password.
The users permissions must be used to determine the proper page

Solution:

Have a look at the post_login method of RootController. Change the
last few lines to

userid = request.identity['repoze.who.userid']
if came_from.decode() == '/':
   came_from = tg.url(get_userpage(userid))
flash(....)
redirect(came_from)

get_userpage should contain your page access logic and return a url
string based on userid

ip address of the user/visitor

in paster, the IP isn't passed in the environment:

       import os
       print os.environ['REMOTEHOST']

in wsgi, the IP is passed in the environment:

       import os
       print os.environ['REMOTE_ADDR']

With webob, I believe you can access the request object directly and
get the remote IP address:

http://turbogears.org/2.0/docs/modules/thirdparty/webob.html

Custom Tg2 Index for your product

You can achieve this by creating a custom index-page that you restrict
easy_install to use when fetching eggs to install. For that, put a line like

[easy_install]
find_links = http://eggbasket.office.ableton.com/versionset/81
allow_hosts = eggbasket.office.ableton.com

into setup.cfg parallel to setup.py in your project.

We do so by having a customizied EggBasket that supports a thing we call
versionsets. And a commandline-tool called Easterbunny that uploads a
virtualenv as whole, making it one of those versionsets.

This works extremely smooth for us for a year now.

Other options also exist, zc.buildout works also AFAIK, but I never toyed
around with that.

semi-dynamic tw forms

  • If you have a list of fields you want to create a widget for you can create it this way:

some_list=['FirstName','LastName','Address']

my_widgets=[]
for k in some_list:
            my_widgets.append(TextField(k,validator=NotEmpty))
        my_form=TableForm('my_form',action='save',children=my_widgets)
  • First line creates a list object.
  • The for loop goes through the list and creates Textfield. Note that names cannot have a space nor special characters like '-', etc.
  • my_form creates the actual form that you can display.

Serving files and its mime type

If 

"""
   @expose(content_type=CUSTOM_CONTENT_TYPE)
   def image(self, id):
         image = Image.get(id)
         pylons.request['Content-Type'] = image.mime_type
         return image.data
"""

So, instead of "image.mime_type", "mimetyes.guess_type(filename)[0]".

General Errors

Addition modules required

ImportError: No module named MySQLdb

Fixed with:

easy_install MySQL-python

ToscaWidget conflict

  Installed /home/lek/work/mine/tg2env/lib/python2.6/site-packages/tw.forms-0.9.7.2-py2.6.egg
  error: Installed distribution ToscaWidgets 0.9.7.1 conflicts with requirement ToscaWidgets>=0.9.7.2
  • Fixed with:

easy_install -U tw.forms

MyWiki: TurboGears2/faq (last edited 2011-02-02 19:40:03 by LukaszSzybalski)