def render_game(room_id): game = ChessGame(room_id) image_path = 'dynamic-images/' + room_id + '.png' print 'Saving to ' + image_path render(game, image_path) return static_file(image_path, root='.')
def update(model): render(model) while True: for player in ('X', 'O'): if is_game_over(model): return do_next_turn(model, player) render(model)
def view(self, header_names, lines, vertical_header=None, initial_sort=[], decimal_points=3): sub_views = [] conv_lines = [] # turn lines to html for line in lines: conv_line, sub_sub_views = convert_to_html(line) conv_lines.append(conv_line) sub_views += sub_sub_views conv_sort = [] for s in initial_sort: dir = 0 if s[1] == 'asc': dir = 0 elif s[1] == 'desc': dir = 1 else: raise Exception('Sort must either be asc or desc') conv_sort.append('[%d,%d]' % (header_names.index(s[0]), dir)) conv_sort = ', '.join(conv_sort) conv_sort = '[%s]' % conv_sort data = OrderedDict() for i in xrange(len(header_names)): data[header_names[i]] = [l[i] for l in conv_lines] html = render('table.html', { 'vertical_header' : vertical_header, 'data' : data, 'id' : self._get_unique_id(), 'header_names': header_names, 'lines': conv_lines, 'sort': conv_sort}) v = View(self, html, ['table.css'], ['jquery.tablesorter.js']) for sub in sub_views: v.append_view_files(sub) return v
def view(self, text, apply, predefined_values=[], id=None, numeric_validation=True, comment='', non_empty_validation=True, size=20): if not id: id = self._get_unique_id() val = '' if self.values.value: val = self.values.value html = render( 'input.html', { 'size': size, 'id': id, 'value': str(val), 'saver_id': apply.id, 'text': text, 'predefined_values': predefined_values, 'numeric_validation': numeric_validation, 'non_empty_validation': non_empty_validation, 'comment': comment, 'widget_id': self.id }) v = View(self, html, [], []) return v
def build(locations, roles, schedule, startDate, tab): """ Formats the given data and generates the html page """ calendar = "" def curTab(day): return "curTab" if day == tab else "tab" params = { "%PREV_WEEK%":util.startOfPrevWeek(startDate), "%NEXT_WEEK%":util.startOfNextWeek(startDate), "%START_WEEK%":util.toDateStr(util.startOfWeek(startDate),True), "%END_WEEK%":util.toDateStr(util.endOfWeek(startDate),True), "%M%": curTab(0), "%T%": curTab(1), "%W%": curTab(2), "%R%": curTab(3), "%F%": curTab(4), "%S%": curTab(5), } #build the calendar for i,day in enumerate(schedule): calendar += buildDay(locations, roles, day, util.addDays(startDate, i)) #add the body of the page params["%CAL_BODY%"] = calendar return view.render("ui/webCal.html", params, tab=tab)
def site_not_found(url): def is_safe(url): import string SAFE = string.digits+string.letters+'_~-' for c in url: if c not in SAFE: return False return True if len(url) < 3 or not is_safe(url): return web.seeother('http://jottit.com') if web.ctx.method == 'POST' and web.ctx.path == '/': mode = pages['index']() return getattr(mode, 'POST')() timestamp, spinner, spinfield = auth.spinner('front page') public_url = secret_url = '' if jt.access == 'public': public_url = url else: secret_url = url web.ctx.status = '404 Not Found' return view.render('site_not_found', vars=locals())
def site_not_found(url): def is_safe(url): import string SAFE = string.digits + string.letters + '_~-' for c in url: if c not in SAFE: return False return True if len(url) < 3 or not is_safe(url): return web.seeother('http://jottit.com') if web.ctx.method == 'POST' and web.ctx.path == '/': mode = pages['index']() return getattr(mode, 'POST')() timestamp, spinner, spinfield = auth.spinner('front page') public_url = secret_url = '' if jt.access == 'public': public_url = url else: secret_url = url web.ctx.status = '404 Not Found' return view.render('site_not_found', vars=locals())
def GET(self): login = LoginAccountForm() create = CreateAccountForm() mast = masthead.index().GET("Mathew") logged_in = web.ctx.session.get("loggedIn") return render("header.mako", login=login, create=create, mast=mast, logged_in=logged_in)
def signin_required(): f = forms.signin() return_to = web.lstrips(web.ctx.fullpath, '/') if not jt.site.public_url: return_to = web.lstrips(return_to, jt.site.secret_url + '/') f.fill(secret_url=jt.site.secret_url, return_to=return_to) page_title = 'Please enter the site-wide password' return view.render('signin', vars=locals())
def GET(self): login = LoginAccountForm() create = CreateAccountForm() mast = masthead.index().GET('Mathew') logged_in = web.ctx.session.get('loggedIn') return render('header.mako', login=login, create=create, mast=mast, logged_in=logged_in)
def signin_required(): f = forms.signin() return_to = web.lstrips(web.ctx.fullpath, '/') if not jt.site.public_url: return_to = web.lstrips(return_to, jt.site.secret_url+'/') f.fill(secret_url=jt.site.secret_url, return_to=return_to) page_title = 'Please enter the site-wide password' return view.render('signin', vars=locals())
def new(self, *args, **kwa): try: schema.to_python(dict(web.input())) except formencode.Invalid, error: return htmlfill.render( render(html), defaults=error.value, errors=error.error_dict )
def view(self, center, left): html = render('leftpanel.html', { 'id' : self._get_unique_id(), 'center' : center.main_html, 'left' : left.main_html}) v = View(self, html, [], []) v.append_view_files(center) v.append_view_files(left) return v
def view(self, text='Apply'): html = render('applybutton.html', { 'text': text, 'id': self._get_unique_id(), 'widget_id': self.id }) v = View(self, html, ['ui-lightness/jquery-ui-1.8.11.custom.css'], ['jquery.blockUI.js']) return v
def GET(self): u = web.input() pg = 'pg=' + u['pg'] if 'pg' in u else '' sl = '&sl=' + u['sl'] if 'sl' in u else '' img = '&with_img=' + u['with_img'] if 'with_img' in u else '' srch = u['searchd'] if 'searchd' in u else None rp = parts_model.Sites().view_entry(u['list_id']) return render('part_view.mako', rp=rp.fetchall(), pg=pg, sl=sl, img=img, srch=srch, list_id=u['list_id'])
def view(self, text='Apply'): html = render('applybutton.html', { 'text' : text, 'id' : self._get_unique_id(), 'widget_id' : self.id}) v = View( self, html, ['ui-lightness/jquery-ui-1.8.11.custom.css'], ['jquery.blockUI.js']) return v
def view(self, collapsed_view, expanded_view): html = render('miniexpander.html', { 'widget_id' : self.id, 'id' : self._get_unique_id(), 'collapsed' : collapsed_view.main_html, 'expanded' : expanded_view.main_html, 'shown' : self.values.shown == 'shown'}) v = View(self, html, [], []) v.append_view_files(collapsed_view) v.append_view_files(expanded_view) return v
def view(self, center, left): html = render( 'leftpanel.html', { 'id': self._get_unique_id(), 'center': center.main_html, 'left': left.main_html }) v = View(self, html, [], []) v.append_view_files(center) v.append_view_files(left) return v
def get(event, context): end = datetime.utcnow() start = end - timedelta(minutes=10) datasets = [] for rule in RULES: app_name = rule.get("application") data = get_data(context, app_name, rule.get('rule'), start, end) datasets.append({'application_name': app_name, 'children': data}) table = render(datasets) return {"html": table}
def view(self, fig, id=None, small_ticks=True): """ fig is a matplotlib figure, which can be created using methods in the axes module (or using matplotlib). It is possible to give and id to the figure, and then refer to this id when attaching an areaselect widget to the Figure. """ if small_ticks: for ax in fig.get_axes(): axes.small_ticks(ax) if not id: id = self._get_unique_id() image_filename = '%s.png' % id full_filename = os.path.join(settings.FREECELL_DIR, 'temp', image_filename) def on_draw(event): fig = event.canvas.figure ax = fig.axes[0] self.data_point1 = (0,0) self.data_point2 = (1,1) # The conversion between pixels and data is linear, so we try to get # the line parameters. This has to be done in the draw event of the print. # (Otherwise the transData misbehaves) self.pixel_point1 = ax.transData.transform(self.data_point1) self.pixel_point2 = ax.transData.transform(self.data_point2) canvas = FigureCanvasAgg(fig) canvas.mpl_connect('draw_event', on_draw) canvas.print_figure(full_filename, dpi=DPI) data = {} # The values calculated here are of the linear formula used to convert pixel to data point and vice versa. # This is used by AreaSelect. data['a_pixel_x'], data['b_pixel_x'] = get_line_parameters(self.data_point1[0], self.pixel_point1[0], self.data_point2[0], self.pixel_point2[0]) data['a_pixel_y'], data['b_pixel_y'] = get_line_parameters(self.data_point1[1], self.pixel_point1[1], self.data_point2[1], self.pixel_point2[1]) data['a_data_x'], data['b_data_x'] = get_line_parameters(self.pixel_point1[0], self.data_point1[0], self.pixel_point2[0], self.data_point2[0]) data['a_data_y'], data['b_data_y'] = get_line_parameters(self.pixel_point1[1], self.data_point1[1], self.pixel_point2[1], self.data_point2[1]) data['pixel_width'] = fig.get_size_inches()[0] * DPI data['pixel_height'] = fig.get_size_inches()[1] * DPI data['id'] = id data['id_function'] = id.replace('-','_') html = render('figure.html', data) with open(full_filename, 'rb') as f: imgdata = f.read() return View( self, html, [], [], {image_filename : imgdata})
def view(self, collapsed_view, expanded_view): html = render( 'miniexpander.html', { 'widget_id': self.id, 'id': self._get_unique_id(), 'collapsed': collapsed_view.main_html, 'expanded': expanded_view.main_html, 'shown': self.values.shown == 'shown' }) v = View(self, html, [], []) v.append_view_files(collapsed_view) v.append_view_files(expanded_view) return v
def view(self, nodes, edges): """ Displays the graph. Format for node: (id, label, score). Format for edge: (label, score, source, target, is_directed) """ nodes = [Node(*n) for n in nodes] edges = [Edge(*e) for e in edges] html = render('graph.html', { 'id' : self._get_unique_id(), 'nodes' : nodes, 'edges' : edges}) v = View(self, html, ['graph.css'], ['json2.js', 'AC_OETags.js', 'cytoscapeweb.js']) return v
def GET(self): from view import render from view import View reports = [ # {'name': 'Population Report', # 'type': 'PopulationReport', # 'description': 'Function plots for the 15 pairs with the highest mutual information.'}, # {'name': 'Histogram Report', # 'type': 'HistogramReport', # 'description': '1D histograms for markers.'}, {'name': 'Chain', 'type': 'Chain', 'description': 'Create a custom chain.'}] return View(None, render('welcome.html', {'reports' : reports})).create_page()
def view(self, figure_id, min_x_id, max_x_id, min_y_id, max_y_id, range): data = { 'id' : self._get_unique_id(), 'figure_id' : figure_id, 'figure_id_func' : figure_id.replace('-', '_'), 'min_x_id' : min_x_id, 'max_x_id' : max_x_id, 'min_y_id' : min_y_id, 'max_y_id' : max_y_id, 'min_x' : range[0] - 0.0001, 'max_x' : range[2] - 0.0001, 'min_y' : range[1] + 0.0001, 'max_y' : range[3] + 0.0001} html = render('areaselect.html', data) return View(self, html, ['imageareaselect/imgareaselect-default.css'], ['jquery.imgareaselect.js'])
def view(self, nodes, edges): """ Displays the graph. Format for node: (id, label, score). Format for edge: (label, score, source, target, is_directed) """ nodes = [Node(*n) for n in nodes] edges = [Edge(*e) for e in edges] html = render('graph.html', { 'id': self._get_unique_id(), 'nodes': nodes, 'edges': edges }) v = View(self, html, ['graph.css'], ['json2.js', 'AC_OETags.js', 'cytoscapeweb.js']) return v
def view(self, figure_id, min_x_id, max_x_id, min_y_id, max_y_id, range): data = { 'id': self._get_unique_id(), 'figure_id': figure_id, 'figure_id_func': figure_id.replace('-', '_'), 'min_x_id': min_x_id, 'max_x_id': max_x_id, 'min_y_id': min_y_id, 'max_y_id': max_y_id, 'min_x': range[0] - 0.0001, 'max_x': range[2] - 0.0001, 'min_y': range[1] + 0.0001, 'max_y': range[3] + 0.0001 } html = render('areaselect.html', data) return View(self, html, ['imageareaselect/imgareaselect-default.css'], ['jquery.imgareaselect.js'])
def GET(self): from view import render from view import View reports = [ # {'name': 'Population Report', # 'type': 'PopulationReport', # 'description': 'Function plots for the 15 pairs with the highest mutual information.'}, # {'name': 'Histogram Report', # 'type': 'HistogramReport', # 'description': '1D histograms for markers.'}, { 'name': 'Chain', 'type': 'Chain', 'description': 'Create a custom chain.' } ] return View(None, render('welcome.html', {'reports': reports})).create_page()
def view(self, header_names, lines, vertical_header=None, initial_sort=[], decimal_points=3): sub_views = [] conv_lines = [] # turn lines to html for line in lines: conv_line, sub_sub_views = convert_to_html(line) conv_lines.append(conv_line) sub_views += sub_sub_views conv_sort = [] for s in initial_sort: dir = 0 if s[1] == 'asc': dir = 0 elif s[1] == 'desc': dir = 1 else: raise Exception('Sort must either be asc or desc') conv_sort.append('[%d,%d]' % (header_names.index(s[0]), dir)) conv_sort = ', '.join(conv_sort) conv_sort = '[%s]' % conv_sort data = OrderedDict() for i in xrange(len(header_names)): data[header_names[i]] = [l[i] for l in conv_lines] html = render( 'table.html', { 'vertical_header': vertical_header, 'data': data, 'id': self._get_unique_id(), 'header_names': header_names, 'lines': conv_lines, 'sort': conv_sort }) v = View(self, html, ['table.css'], ['jquery.tablesorter.js']) for sub in sub_views: v.append_view_files(sub) return v
def POST(self): login = LoginAccountForm(Request().POST) create = CreateAccountForm() if login.validate() != True: return render('index.mako', login=login, create=create) post = web.input() import hashlib password = hashlib.sha1(post.password).hexdigest() mongo_query = db.users.find_one({'name' : post.username, 'password' : password}) if mongo_query: user = mongo_query['_id'] else: user = False return sa.login({ 'check' : mongo_query, 'redirect_to_if_pass' : '../welcome/', 'redirect_to_if_fail' : '../', 'user' : user })
def POST(self): login = LoginAccountForm(Request().POST) create = CreateAccountForm() if login.validate() != True: return render('site_admin.mako', site_type='login', login=login, create=create) post = web.input() import hashlib psswrd = hashlib.sha1(post.password).hexdigest() query = db.users.filter_by(name=post.username, password=psswrd).first() if query: user = query.id else: user = False return sa.login({ 'check' : query, 'redirect_to_if_pass' : '../welcome/', 'redirect_to_if_fail' : '../', 'user' : user })
def build( appointmentList, startOfWeek, location ): """ Formats and returns the html for the detailed list appointmentList - a list of days, each day is a list of appointments for that day startOfWeek - a datetime object that represents the start of the week location - the location to list the appointments for """ DAY_TEMPLATE = "<li class=\"important\">%s %s</li>\n" APP_TEMPLATE = "<li><a %s href=\"editAppointment?name=%s&time=%s\">%s %s %s</a></li>\n" EMPTY_TEMPLATE = "<li><a href=\"editAppointment?time=%s\">No Appointments</a></li>\n" appList = "" params = {"%LOCATION%":location} #display the appointments for each day for i,dayList in enumerate(appointmentList): datetime = util.addDays(startOfWeek, i) #generate the header for the day appList += DAY_TEMPLATE % ( util.toDayName(datetime), util.toDateStr(datetime, True) ) #if there are any appointments for the day then show them if len(dayList): #generate the html for each appointment for app in sorted(dayList, timeCompare): appList += APP_TEMPLATE % ("class=\"booked\"" if app.isBooked() else "", app.staffName, app.time, app.getFTime(), app.staffName, "- " + app.description if app.description else "") #else show a place holder else: appList += EMPTY_TEMPLATE % datetime #add the scheduled appointments to the page params["%THE_LIST%"] = appList return view.render("ui/daydetails.html", params)
def view(self, text, apply, predefined_values=[], id=None, numeric_validation=True, comment='', non_empty_validation=True, size=20): if not id: id = self._get_unique_id() val = '' if self.values.value: val = self.values.value html = render('input.html', { 'size' : size, 'id' : id, 'value' : str(val), 'saver_id' : apply.id, 'text' : text, 'predefined_values' : predefined_values, 'numeric_validation' : numeric_validation, 'non_empty_validation' : non_empty_validation, 'comment' : comment, 'widget_id' : self.id}) v = View( self, html, [], []) return v
def POST(self): i = web.input() job_form = AddJob(Request().POST) user_id = web.ctx.session.user_id name = db.users.filter_by(id=user_id).first().name jobs = db.jobs.all() if job_form.validate() is True: start_date = i.start_date.split("/") day = int(start_date[0]) month = int(start_date[1]) year = int(start_date[2]) time = DateTime(year, month, day, 0, 0, 0) db.jobs.insert(job_nm=i.job_name, job_desc=i.job_desc, job_date_start=time.ticks()) try: db.commit() except: db.rollback() web.redirect('../welcome/') else: return render('welcome.mako', name=name, jobs=jobs, job_form=job_form)
def view(self, center, west=None, north=None, east=None, south=None): def convert_to_html_or_none(sub_item): if sub_item == None: return None, [] html,views = convert_to_html([sub_item]) html = ''.join(html) return html,views center_html, center_views = convert_to_html_or_none(center) west_html, west_views = convert_to_html_or_none(west) north_html, north_views = convert_to_html_or_none(north) east_html, east_views = convert_to_html_or_none(east) south_html, south_views = convert_to_html_or_none(south) html = render('layout.html', { 'id' : self._get_unique_id(), 'center_html' : center_html, 'west_html' : west_html, 'north_html' : north_html, 'east_html' : east_html, 'south_html' : south_html}) v = View(self, html, ['layout-default-latest.css'], ['jquery.layout-latest.js']) for sub in sum([center_views, west_views, north_views, east_views, south_views], []): v.append_view_files(sub) return v
def GET(self): user_id = web.ctx.session.user_id name = db.users.filter_by(id=user_id).first().name jobs = db.jobs.order_by(desc(db.jobs.job_id)).all() job_form = AddJob() return render('welcome.mako', name=name, jobs=jobs, job_form=job_form)
def render(self, filename, data): data = self.prepare(data) view.render(self, filename, data)
def GET(self): u = web.input() search_query = u['searchd'] auth = u['auth'] if 'auth' in u else None site = u['site'] if 'site' in u else None if 'pg' in u: page_num = u['pg'] else: page_num = 0 id_select = None srch_term_sphx = None display_term = None num_rows = None time = None limit = 20 if not search_query: raise web.seeother('../') sc = sphinxapi.SphinxClient() sc.SetServer("127.0.0.1", 3312) sc.SetMatchMode(sphinxapi.SPH_MATCH_ALL) sc.SetSortMode(sphinxapi.SPH_SORT_RELEVANCE) sc.SetSortMode(sphinxapi.SPH_SORT_ATTR_DESC, 'post_date') sc.SetLimits(int(page_num) * 10, limit) def get_collected_ids(sq): res = sc.Query(sq, index="posts") matched_ids = res['matches'] total_found = res['total_found'] collected_ids = [str(i['id']) for i in matched_ids] id_select = ','.join(collected_ids) return id_select, total_found def getID(cleansed_ids, sql_type=False): if sql_type is "site_nm": sql_id = """SELECT site_id FROM site WHERE site_nm IN (%(site_select)s)""" % ({'site_select': cleansed_ids}) if sql_type is "auth_nm": sql_id = """SELECT auth_id FROM author WHERE auth_nm IN (%(auth_select)s)""" % ({'auth_select': cleansed_ids}) id_rows = db.bind.execute(sql_id) return [int(i[0]) for i in id_rows] def splitify(target_id, key=False): if target_id: t_id = dict([(i.strip().split(":")[0], i.strip().split(":")[1]) for i in re.split('(@[a-zA-Z]+(:[a-zA-Z,-_|]+))', target_id) if re.search('@(\w+)', i)]) if key in t_id: return t_id[key].split("|") search_query = search_query.strip() if re.compile('(@[a-zA-Z]+)').findall(search_query): print "advance query" srch_terms = re.split('(@[a-zA-Z]+(:[a-zA-Z,-_|]+))', search_query) terms = [i.strip() for i in srch_terms if not re.search('(:\w+)', i)] terms = [i for i in terms if i] terms = terms[0] if terms else "" siteid = splitify(site, key="@site") authid = splitify(auth, key="@auth") #srch_ttle = "@title " + " ".join(srch_hash['@title'].split(",")) if '@title' in srch_hash else None #srch_body = "@body " + " ".join(srch_hash['@body'].split(",")) if '@body' in srch_hash else None site_ids_db = getID(",".join(["'%s'" % i.upper() for i in siteid]), sql_type="site_nm") if siteid else None auth_ids_db = getID(",".join(["'%s'" % i for i in authid]), sql_type="auth_nm") if authid else None if siteid and site_ids_db: print "filtering by site ids" sc.SetFilter('site_id', site_ids_db) if authid and auth_ids_db: print "filtering by auth ids" sc.SetFilter('auth_id', auth_ids_db) srch_term_sphx = terms display_term = search_query gci = get_collected_ids(srch_term_sphx) id_select = gci[0] num_rows = gci[1] else: print "basic query" srch_term_sphx = search_query display_term = search_query gci = get_collected_ids(search_query) id_select = gci[0] num_rows = gci[1] pg = Pageset(num_rows, limit) pg.current_page(pg) pages = pg.pages_in_set() first = pg.first_page() last = pg.last_page() sk = SkuInfo() ids_listinfo = sk.sku_info(id_select, srch_term_sphx, sc) if id_select else None return ids_listinfo return render('search_results.mako', rp=ids_listinfo, search_term=display_term, pages=pages, first=first, last=last, current_page=int(page_num) , limit=limit, auth=auth, site=site, num_rows=num_rows)
def get(self, leaderboard_id): qry = LeaderboardEntry.query() qry = qry.filter(LeaderboardEntry.leaderboard_id == leaderboard_id) qry = qry.order(-LeaderboardEntry.score) scores = qry.fetch(100) view.render(self, 'leaderboard.html', scores=scores)
def POST(self): frm = CreateAccountForm(Request().POST) if frm.validate() != True: return render('welcome.mako', frm=frm) return web.input()
def GET(self): user_id = web.ctx.session['user_id'] return render('welcome.mako', user_id=user_id)
def view(self, report_id): html = render('freecellmenu.html', {'report_id': report_id}) v = View(self, html, [], []) return v
from view import render render()
def GET(self): return render('index.mako')
def view(self, text, save_button, options, multiple=True, group_buttons=[], choices=None, comment=''): """ Returns a view of the select widget. text is a the title of the widget. save_button is an ApplyButton used to save the widget's state. options describes the options in the select box. options can be: 1. a list of strings --> one selection group, titles and values are the same, none is selected 2. a list of (value, title) tuples --> one selection group, titles and values are different, none is selected 3. a list of (value, title, selected) tuples --> one selection group, titles and values are different, selection according to selected. 3. a list of (group_name, 1/2/3 style list) --> multiple groups. groups is a list of tuples of (group_name, list of vals). If it is not None, then a button is added for every group. When the button is pressed, the relevant items are selected. comment -- displays text next to the select box. """ def add_titles_if_needed(items): if items and type(items[0]) != tuple: items = zip(items, items) return items def add_selected_state(items): choices_as_str = [str(x) for x in choices] return [(o[0], o[1], str(o[0]) in choices_as_str) for o in items] if choices == None: choices = self.values.choices if choices == None: choices = [] if not options: options = [] else: options = add_titles_if_needed(options) #print options # Now options is either a list of title,val or a list of (group_name, group_values) if not type(options[0][1]) in (tuple, list): options = [('None', options)] #print options # Now options is either a list of (group_name, list(titles)) or a list of (group_name, list(titles, vals)) options = [(o[0], add_titles_if_needed(o[1])) for o in options] #print options # Now add selected state the list so that we have (group_name list(titles, vals, select)) options = [(o[0], add_selected_state(o[1])) for o in options] #print options html = render( 'select.html', { 'height': 300, 'groups': group_buttons, 'text': text, 'saver_id': save_button.id, 'id': self._get_unique_id(), 'multiple': multiple, 'items': options, 'comment': comment, 'widget_id': self.id }) v = View(self, html, ['jquery.multiselect.css'], ['jquery.multiselect.js']) return v
def POST(self): login = LoginAccountForm() create = CreateAccountForm(Request().POST) if create.validate() != True: return render('index.mako', login=login, create=create) return web.input()
def GET(self): u = web.input() pg, sl, with_img = u['pg'] if 'pg' in u else None, u['sl'] if 'sl' in u else None, u['with_img'] if 'with_img' in u else None current_page = int(pg) sites_for_now = parts_model.Sites().show_sites() if sl: new_sites = [] for site in sl.split(","): new_sites.append("'%s'" % site) sites_for_now = new_sites site_select = ",".join(sites_for_now) img_post_ids = "" if with_img: sk = SkuInfo() sk.cl.SetLimits(0, 1000) res = sk.cl.Query('.jpg') img_post = [("'%s'" % i['id']) for i in res['matches']] img_post_ids = "AND SUBSTRING_INDEX( SUBSTRING_INDEX(listings_posts.idlistings_posts, ':', 2), ':', -1) IN (" + ",".join(img_post) + ")" values = {'site_select': site_select, 'img': img_post_ids} sc = sphinxapi.SphinxClient() sc.SetServer("127.0.0.1", 3312) #sc.SetSortMode(sphinxapi.SPH_SORT_ATTR_DESC, "post_date") sql_id = """SELECT site_id FROM site WHERE site_nm IN (%(site_select)s)""" % ({'site_select': site_select}) id_rows = db.bind.execute(sql_id) site_ids = [int(i[0]) for i in id_rows] limit = 50 sc.SetFilter('site_id', site_ids) #sc.SetLimits(int(pg) * 10, limit) res = sc.Query("") num_rows = res['total_found'] pg = Pageset(num_rows, limit) pg.current_page(current_page) option_select_key = "%s:%s:%s" % (":".join(sites_for_now), pg.skipped(), pg.entries_per_page()) option_select_key_browse = "%s:%s:%s:browse" % (":".join(sites_for_now), pg.skipped(), pg.entries_per_page()) #sk = SkuInfo() #ids_list = sk.sku_info(','.join([str(i['id']) for i in res['matches']]), None, sc) # d = OrderedDict() # for i in ids_list: # d.setdefault(i['date'], []) # d[i['date']].append((i['title'], i['sku'])) if r_server.get(option_select_key): print "cache_hit:browsedata-date:retrieve" date_result = cPickle.loads(str(r_server.get(option_select_key))) else: print "cache_hit:browsedata-date:set" date_sql = """ SELECT dp.list_date AS list_date , dp.list_title AS title , dp.list_sku AS sku , SUBSTRING_INDEX( SUBSTRING_INDEX(lp.idlistings_posts, ':', 2), ':', -1) AS post_id FROM ( SELECT list_date, list_title, list_sku FROM data_prep WHERE 1=1 AND SUBSTRING_INDEX(list_sku, ":", 1) IN (%(site_select)s) ) AS dp INNER JOIN ( SELECT list_sku, idlistings_posts FROM listings_posts WHERE 1=1 AND list_starter = 1 ) As lp ON lp.list_sku = dp.list_sku ORDER BY list_date DESC LIMIT %(offset)i, %(limit)i """ % ({'site_select': site_select, 'offset': pg.skipped(), 'limit': pg.entries_per_page()}) date_result = db.bind.execute(date_sql).fetchall() r_server.set(option_select_key, cPickle.dumps(date_result)) pages = pg.pages_in_set() first = pg.first_page() last = pg.last_page() sites_alpha = parts_model.Sites().show_sites(with_quotes=False) chosen = [] if sl: chosen = sl.split(',') if chosen != None: remaining = filter(lambda x : x not in chosen, sites_alpha) else: remaining = sites_alpha selected = filter(lambda x : x in chosen, sites_alpha) connect_str = "" if len(selected) == 1 or len(selected) == 0 else "&sl=" img_str = "&with_img=1" if with_img else "" img_str_sl = "&sl=" if len(selected) > 0 else "" if r_server.get(option_select_key_browse): print "cache_hit:browsedata-browse:retrieve" d = cPickle.loads(str(r_server.get(option_select_key_browse))) else: print "cache_hit:browsedata-browse:set" d = OrderedDict() for i in date_result: d.setdefault(i[0], []) d[i[0]].append((i[1], i[2])) r_server.set(option_select_key_browse, cPickle.dumps(d)) r_server.expire(option_select_key, cache_timeout) r_server.expire(option_select_key_browse, cache_timeout) return render('browse_view.mako', pages=pages, date_result=d, first=first, last=last, current_page=current_page, sl=sl, with_img=with_img, chosen=chosen, remaining=remaining, selected=selected, connect_str=connect_str, img_str_sl=img_str_sl, img_str=img_str)
def view(self, col_names, data, time_strings, comment='', height=600, width=800): """Draws the motion chart. col_names is a list of column names, data is a list of rows (each row is a list of strings). The first column is the entity name (string). The second column is a time column, and should be a number. Other columns can be either numbers or strings. time_strings is a string representation for the timestamp number (time is the index). Note: This relies on the google api being loaded in the main page, i.e that we have a script tag that loads https://www.google.com/jsapi in the head section. """ col_types = [] if (self.last_col_names and self.last_col_names != col_names): # If the columns were changed, we need to reset the state. self.values.state = None self.last_col_names = col_names # The motion chart flash can't handle characters like + in the id column. # We change those characters (only + for now) and save a map from the # modified id to the original id. self.id_map = {} for i, row in enumerate(data): data[i] = list(row) old_id = data[i][0] new_id = old_id.replace('+', 'hi') data[i][0] = new_id self.id_map[new_id] = old_id first_row = data[0] for val in first_row: if type(val) in (str, unicode): col_types.append('string') elif type(val) in (int, float, np.float64): col_types.append('number') else: raise ValueError('Unsupported type %s' % str(type(val))) col_names_types = zip(col_names, col_types) json_data = json.dumps(data) print self.values.state html = render( 'motionchart.html', { 'widget_id': self.id, 'id': self._get_unique_id(), 'comment': comment, 'height': height, 'width': width, 'json_data': json_data, 'col_names_types': col_names_types, 'time_strings_json': json.dumps(time_strings), 'state': self.values.state }) v = View(self, html, ['jquery.multiselect.css'], ['jquery.multiselect.js']) return v
def site_deleted(): web.ctx.status = '404 Gone' # lighttpd doesn't like 410s return view.render('site_deleted', vars=locals())