Probleme mit dem Beispiel aus dem TurboGears Buch

Sockets, TCP/IP, (XML-)RPC und ähnliche Themen gehören in dieses Forum
Antworten
data18
User
Beiträge: 1
Registriert: Dienstag 24. Juli 2007, 21:15

Dienstag 24. Juli 2007, 21:31

Hallo,
ich arbeite gerade das TurboGears durch und hänge an dem Beispiel
Bookmark Application.

Vielleicht hat ja jemand schon an dem gleichen Problem gehangen.

Code: Alles auswählen

import logging
import cherrypy
import turbogears
#from turbogears import controllers, identity, expose, widgets, validators
from turbogears import controllers, identity, expose, flash, validate, redirect, widgets, validators, error_handler
from turbogears.toolbox import catwalk
from model import Bookmarks, Categories

def get_category_options():
    categories = Categories.select()
    options = []
    for category in categories:
        options.append((category.id, category.categoryName))
    return options

class bookmark_fields(widgets.WidgetsList):
    name = widgets.TextField(validator=validators.NotEmpty)
    link = widgets.TextField(validator=validators.URL)
    description = widgets.TextArea(validator=validators.NotEmpty)
    select_categories = widgets.SingleSelectField(options=get_category_options())

bookmark_form = widgets.TableForm(fields=bookmark_fields(), submit_text="Bookmark speichern")

class Root(controllers.RootController):
    @expose(template="bookmarker.templates.index")
    def index(self):
        return dict()
        
    @expose(template="bookmarker.templates.list")
    def list(self):
        b=Bookmarks.select()
        return dict(bookmark=b)
    
    @expose(template="bookmarker.templates.categorylist")
    def list_by_category(self):
        cat=Categories.select()
        return dict(categories=cat)
    
    @expose(template="bookmarker.templates.form")
    def bookmark(self, *args, **kwargs):
        if args and args[0] == "add":
            values = []
            submit_action= "/save_bookmark/"
        if args and args[0] == "edit":
            try:
                b = Bookmarks.get(args[1])
                default_options = []
                for a in b.categories:
                    default_options.append(a.id)
                values = {"name" : b.name, "link": b.link, "description": b.description, "select_categories": default_options}
            except:
                values = ""
                flash = "That's not a valid Bookmark, do you want to add one now?"
            submit_action = "/save_bookmark/edit/%s" %args[1]
        return dict(form=bookmark_form, values=values, action=submit_action)

    @expose()
    @error_handler(bookmark)
    @validate(form=bookmark_form)
    def save_bookmark(self, *args, **kwargs):
        try:
            b=Bookmarks.get(args[1])
            b.name=kwargs["name"]
            b.link = kwargs["link"]
            b.description = kwargs["description"]
            Bookmarks.UpdateCategories(b,kwargs["select_categories"])
        except:
            b=Bookmarks(name=kwargs["name"], link = kwargs["link"], description = kwargs["description"])
            for item in kwargs["select_categories"]:
                b.addCategories(Categories.get(item))
        raise cherrypy.HTTPRedirect("/index")
    
    @expose( html=".templates.login")
    def login(self, *args, **kw):
        if hasattr(cherrypy.request, "identity_errors"):
            msg= _("You must provide your credentials before accessing this resource.")
            previous_url= cherrypy.request.path
        else:
            msg= _("Please log in.")
            previous_url= cherrypy.request.headers.get("Referer", "/")
        cherrypy.response.status=403
        return dict(message=msg, previous_url=previous_url, logging_in=True,
                     original_parameters=cherrypy.request.params)

    @expose()
    def logout(self):
        identity.current.logout()
        raise cherrypy.HTTPRedirect(turbogears.url("/"))
Wenn ich nun einen Datensatz hinzufügen will erhalte ich die Fehlermeldung:
File "/opt/Turbogears/bookmarker/bookmarker/controllers.py", line 55, in bookmark
return dict(form=bookmark_form, values=values, action=submit_action)
UnboundLocalError: local variable 'values' referenced before assignment
Man könnte zwar das Problem lösen indem man

Code: Alles auswählen

values= ""
submit_action = ""
vor

Code: Alles auswählen

return dict(form=bookmark_form, values=values, action=submit_action)
einfügt, jedoch funktioniert dann edit nicht mehr. Ich habe diese Beispiel
sogar direkt von turbogearsbook.com heruntergeladen, bekommen aber
die gleiche Fehlermeldung.

Vielleicht kann mir jemand helfen.

Vielen Dank

Grüsse

Alexander

Edit (Leonidas): Code-Highlighting eingeschaltet.
Benutzeravatar
DatenMetzgerX
User
Beiträge: 398
Registriert: Freitag 28. April 2006, 06:28
Wohnort: Zürich Seebach (CH)

Dienstag 24. Juli 2007, 21:39

das problem ist, wenn args[0] != "add" und != "edit" ist

Code: Alles auswählen

if args and args[0] == "add":
            values = []
            submit_action= "/save_bookmark/"
        if args and args[0] == "edit":
            try:
                b = Bookmarks.get(args[1])
                default_options = []
                for a in b.categories:
                    default_options.append(a.id)
                values = {"name" : b.name, "link": b.link, "description": b.description, "select_categories": default_options}
            except:
                values = ""
                flash = "That's not a valid Bookmark, do you want to add one now?"
            submit_action = "/save_bookmark/edit/%s" %args[1]
        else: values = "Action not found..."
        return dict(form=bookmark_form, values=values, action=submit_action)
Antworten