implement URL generation

move code for URL generation to model/urlbuilder.py
add format selection to input form
create output template
This commit is contained in:
Jan Dittberner 2009-01-21 01:11:01 +01:00
parent d86965304f
commit f33f6c7751
7 changed files with 81 additions and 108 deletions

View file

@ -1,7 +1,9 @@
import logging import logging
import simplejson
from ddportfolioservice.lib.base import * from ddportfolioservice.lib.base import *
from ddportfolioservice.model.form import * from ddportfolioservice.model.form import *
from ddportfolioservice.model.urlbuilder import *
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
@ -20,4 +22,9 @@ class DdportfolioController(BaseController):
except formencode.validators.Invalid, error: except formencode.validators.Invalid, error:
c.messages = { 'errors' : error.unpack_errors() } c.messages = { 'errors' : error.unpack_errors() }
return render('/showform.mako') return render('/showform.mako')
return ["done"] data = build_urls(form_result)
if 'mode' in request.params and request.params['mode'] == 'json':
response.headers['Content-Type'] = 'text/json'
return simplejson.dumps(data['data'])
c.urldata = data
return render('/showurls.mako')

View file

@ -1,101 +0,0 @@
# -*- python -*-
# -*- coding: utf8 -*-
from paste.request import parse_formvars
import pkg_resources
import simplejson
from ConfigParser import ConfigParser
from urllib import quote_plus
import logging
import sys
import formencode
from gettext import gettext as _
from formencode import validators
logging.basicConfig(level=logging.DEBUG, stream=sys.stderr)
my_config = ConfigParser()
my_config.readfp(pkg_resources.resource_stream(__name__, 'ddportfolio.ini'))
def build_urls(fields):
"""Build personalized URLs using the developer information in
fields."""
result = {}
qfields = dict([(key, quote_plus(fields[key])) for key in fields])
for section in my_config.sections():
if my_config.has_option(section, 'urls'):
for url in my_config.get(section, 'urls').split(','):
if my_config.has_option(section, url + '.pattern'):
try:
result[section + '.' + url] = \
my_config.get(section, url + '.pattern',
False, qfields)
except Exception, e:
logging.error(_("unable to parse %s: %s") %
(my_config.get(section, url +
'.pattern', True), e))
return result
class DeveloperData(formencode.Schema):
name = validators.String(not_empty=True)
email = validators.Email(not_empty=True)
username = validators.PlainText(not_empty=True)
def validate_input(fields):
logging.debug(fields)
return DeveloperData().to_python(fields)
def gather_additional_info(fields):
logging.debug(fields)
return fields
def application(environ, start_response):
"""WSGI application entry point."""
if environ['REQUEST_METHOD'] == 'POST':
try:
fields = gather_additional_info(
validate_input(parse_formvars(environ)))
except formencode.Invalid, e:
start_response('400 Bad Request', [('content-type', 'text/plain')])
return ["input validation failed\n", e.unpack_errors()]
data = build_urls(fields)
if ('mode' in fields and fields['mode'] == 'json'):
start_response('200 OK', [('content-type', 'text/json')])
return [simplejson.dumps(data)]
else:
start_response('200 OK', [('content-type', 'text/html')])
return ['''<html>
<head><title>''', _("Debian Developer Portfolio"),'''</title></head>
<body>
<ul>
<li>''',
'</li><li>'.join([
'%(key)s: <a href="%(url)s">%(url)s</a>' %
{'key': key, 'url': data[key]} for key in data]),
'</li></ul></body></html>']
else:
start_response('200 OK', [('content-type', 'text/html')])
return ['''<html>
<head>
<title>''', _('Debian Developer Portfolio'), '''</title>
</head>
<body>
<form method="post">
<fieldset id="ddportfolio">
<legend>''', _('Debian Developer Portfolio'), '''</legend>
<label for="name">''', _('Name:'), '''</label><br />
<input type="text" name="name" /><br />
<label for="email">''', _('E-Mail:'), '''</label><br />
<input type="text" name="email" /><br />
<label for="username">''', _('User name:'), '''</label><br />
<input type="text" name="username" /><br />
<input type="submit" value="''', _('Build DD Portfolio URLs'), '''" />
</fieldset>
</form>
</body>
</html>''']
if __name__ == '__main__':
from paste import httpserver
httpserver.serve(application, host='127.0.0.1', port='8080')

View file

@ -26,6 +26,7 @@ class BaseController(WSGIController):
add_fallback(lang) add_fallback(lang)
except: except:
pass pass
c.messages = { 'errors': [], 'messages': [] }
return WSGIController.__call__(self, environ, start_response) return WSGIController.__call__(self, environ, start_response)
# Include the '_' function in the public names # Include the '_' function in the public names

View file

@ -9,13 +9,13 @@ received.pattern=http://bugs.debian.org/%(email)s
reported.pattern=http://bugs.debian.org/from:%(email)s reported.pattern=http://bugs.debian.org/from:%(email)s
bugstats.pattern=http://asdfasdf.debian.net/~tar/bugstats/?%(email)s bugstats.pattern=http://asdfasdf.debian.net/~tar/bugstats/?%(email)s
usertags.pattern=http://bugs.debian.org/cgi-bin/pkgreport.cgi?users=%(email)s usertags.pattern=http://bugs.debian.org/cgi-bin/pkgreport.cgi?users=%(email)s
searchall.pattern=http://merkel.debian.org/~don/cgi/search.cgi?phrase=%(name)s&search=search searchall.pattern=http://merkel.debian.org/~don/cgi/search.cgi?phrase=%(name)s&amp;search=search
wnpp.pattern=http://qa.debian.org/developer.php?wnpp=%(email)s wnpp.pattern=http://qa.debian.org/developer.php?wnpp=%(email)s
[build] [build]
urls=buildd,igloo,svnbuildstat urls=buildd,igloo,svnbuildstat
buildd.pattern=http://buildd.debian.org/pkg.cgi?maint=%(email)s buildd.pattern=http://buildd.debian.org/pkg.cgi?maint=%(email)s
igloo.pattern=http://oldpeople.debian.org/~igloo/status.php?email=%(email)s&thin=on igloo.pattern=http://oldpeople.debian.org/~igloo/status.php?email=%(email)s&amp;thin=on
svnbuildstat.pattern=http://svnbuildstat.debian.net/packages/list/%(email)s svnbuildstat.pattern=http://svnbuildstat.debian.net/packages/list/%(email)s
[qa] [qa]
@ -30,9 +30,9 @@ keylog.pattern=http://merkel.debian.org/~enrico/keylog/%(gpgfp)s.html
[lists] [lists]
urls=dolists,adolists,gmane urls=dolists,adolists,gmane
dolists.pattern=http://lists.debian.org/cgi-bin/search?author=%(name)s&sort=date dolists.pattern=http://lists.debian.org/cgi-bin/search?author=%(name)s&amp;sort=date
adolists.pattern=http://www.google.com/search?q=site%%3Alists.alioth.debian.org+%%22%(name)s%%22 adolists.pattern=http://www.google.com/search?q=site%%3Alists.alioth.debian.org+%%22%(name)s%%22
gmane.pattern=http://search.gmane.org/?email=%(name)s&group=gmane.linux.debian.* gmane.pattern=http://search.gmane.org/?email=%(name)s&amp;group=gmane.linux.debian.*
[files] [files]
urls=people,alioth urls=people,alioth
@ -42,10 +42,10 @@ alioth.pattern=http://alioth.debian.org/~%(username)s/
[membership] [membership]
urls=nm,db,alioth urls=nm,db,alioth
nm.pattern=https://nm.debian.org/nmstatus.php?email=%(email)s nm.pattern=https://nm.debian.org/nmstatus.php?email=%(email)s
db.pattern=http://db.debian.org/search.cgi?uid=%(username)s&dosearch=Search db.pattern=http://db.debian.org/search.cgi?uid=%(username)s&amp;dosearch=Search
alioth.pattern=http://alioth.debian.org/users/%(username)s/ alioth.pattern=http://alioth.debian.org/users/%(username)s/
[miscellaneous] [miscellaneous]
urls=debtags,links urls=debtags,links
debtags.pattern=http://debtags.alioth.debian.org/todo.html?maint=%(email)s debtags.pattern=http://debtags.alioth.debian.org/todo.html?maint=%(email)s
links.pattern=http://www.google.com/search?hl=en&lr=&q=site%%3Adebian.org+%%22%(name)s%%22+-site%%3Anm.debian.org+-site%%3Alintian.debian.org+-site%%3Abugs.debian.org+-site%%3Alists.debian.org+-site%%3Apackages.debian.org+-site%%3Alists.alioth.debian.org+-site%%3Aftp.debian.org++-site%%3Apackages.qa.debian.org++-site%%3Aftp*.*.debian.org+-inurl%%3Adebian.org%%2Fdevel%%2Fpeople.+-inurl%%3Aindices%%2FMaintainers+-inurl%%3Adebian.org%%2Fdebian%%2Fproject++-inurl%%3A%%2Fdists%%2F&btnG=Search links.pattern=http://www.google.com/search?hl=en&amp;lr=&amp;q=site%%3Adebian.org+%%22%(name)s%%22+-site%%3Anm.debian.org+-site%%3Alintian.debian.org+-site%%3Abugs.debian.org+-site%%3Alists.debian.org+-site%%3Apackages.debian.org+-site%%3Alists.alioth.debian.org+-site%%3Aftp.debian.org++-site%%3Apackages.qa.debian.org++-site%%3Aftp*.*.debian.org+-inurl%%3Adebian.org%%2Fdevel%%2Fpeople.+-inurl%%3Aindices%%2FMaintainers+-inurl%%3Adebian.org%%2Fdebian%%2Fproject++-inurl%%3A%%2Fdists%%2F&amp;btnG=Search

View file

@ -0,0 +1,30 @@
# -*- python -*-
# -*- coding: utf8 -*-
import ConfigParser
import pkg_resources
from urllib import quote_plus
my_config = ConfigParser.ConfigParser()
my_config.readfp(pkg_resources.resource_stream(__name__, 'ddportfolio.ini'))
def build_urls(fields):
"""Build personalized URLs using the developer information in
fields."""
data = {}
errors = {}
qfields = dict([(key, quote_plus(fields[key])) for key in fields])
for section in my_config.sections():
if my_config.has_option(section, 'urls'):
for url in my_config.get(section, 'urls').split(','):
if my_config.has_option(section, url + '.pattern'):
try:
data[section + '.' + url] = \
my_config.get(section, url + '.pattern',
False, qfields)
except Exception, e:
errors['%s.%s.pattern' % (section, url)] = \
[my_config.get(section, '%s.pattern' % url,
True), str(e)]
return {'data' : data, 'errors' : errors}

View file

@ -27,6 +27,8 @@
% endif % endif
</label><br /> </label><br />
${h.text_field('username', value=request.params.get('username', None))}<br /> ${h.text_field('username', value=request.params.get('username', None))}<br />
<label for="mode_html">${_('Output format:')}</label><br />
${_('HTML')}&#160;${h.radio_button('mode', 'html', checked=(request.params.get('mode', 'html') == 'html'))}&#160;${_('JSON')}&#160;${h.radio_button('mode', 'json', checked=(request.params.get('mode', 'html') == 'json'))}<br />
${h.submit(value=_('Build DD Portfolio URLs'))} ${h.submit(value=_('Build DD Portfolio URLs'))}
</fieldset> </fieldset>
${h.end_form()} ${h.end_form()}

View file

@ -0,0 +1,34 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>${_('Debian Developer Portfolio')}</title>
${h.stylesheet_link_tag('style')}
</head>
<body>
% if c.urldata['data']:
<fieldset id="ddportfolio">
<legend>${_('Debian Developer Portfolio')}</legend>
<ul>
% for key in c.urldata['data']:
<li>${key}<br />${h.link_to(h.truncate(
c.urldata['data'][key], length=120), c.urldata['data'][key])}</li>
% endfor
</ul>
</fieldset>
% endif
% if c.urldata['errors']:
<fieldset id="ddportfolioerrors">
<legend>${_('Errors during URL creation')}</legend>
<ul>
% for key in c.urldata['errors']:
<li>${key}<br />
<span class="errormsg">${c.urldata['errors'][key][0]}<br />
${c.urldata['errors'][key][1]}</span></li>
% endfor
</ul>
</fieldset>
% endif
<p>${h.link_to(_('Restart'), h.url_for(action='index'))}</p>
</body>
</html>