def setting_view(): template_name = 'setting.html' user = session_user() if user is None: abort(404, _('access denied')) if request_is_get(): user_images = UserProfile_Image.select().where(UserProfile_Image.user == user, UserProfile_Image.is_active == True) return render(template_name, user_images=user_images) if form_get('remove-image'): remove_image_id = form_get('image_id') try: image = UserProfile_Image.get(UserProfile_Image.user == user, UserProfile_Image.id == remove_image_id) except: abort(404) image.is_active = False image.save() return render('redirect.html', url='') profile = UserProfile.get(UserProfile.user == user) user.email = form_get('email', '') user.nickname = form_get('nickname', 'anonymous') profile.body = form_get('body', '') user.save() profile.save() upload_images = request.files.getlist('images[]') upload_images_save('profile', upload_images, user) return render('redirect.html', url=URL['user'].replace('<user_id:int>', str(user.id)))
def search_entry_view(entry_id): template_name = 'search_entry.html' try: entry = Entry.get(Entry.id == entry_id, Entry.is_active == True) except: abort(404) if request_is_get(): entry_images = Entry_Image.select().where(Entry_Image.entry == entry, Entry_Image.is_active == True) entry_comments = Comment.select().where(Comment.entry == entry, Comment.is_active == True) return render(template_name, entry=entry, entry_images=entry_images, entry_comments=entry_comments) user = session_user() if user is None: return render('redirect.html', url=URL['signup']) body = form_get('body') parent = form_get('parent') if body is None: return render('redirect.html', url='') Comment.create( user=user, entry=entry, parent=parent, body=body, ) return render('redirect.html', url='')
def password(request, api, account_info, config, username, saved=False): features = api.enterprise_features() password_form = PasswordForm() if request.method == 'POST': if request.POST.get('form', '') == 'password': password_form = PasswordForm(request.POST) if password_form.is_valid(): new_password = password_form.cleaned_data['password'].encode('utf-8') log_admin_action(request, 'change password') new_pass, api_pass = hash_password(new_password) api.update_enterprise_password(api_pass) config_mgr_ = config_mgr.ConfigManager(config_mgr.default_config()) config_mgr_.config['api_password'] = api_pass config_mgr_.config['local_password'] = new_pass config_mgr_.apply_config() return redirect('blue_mgnt:password_saved') return render(request, 'password.html', dict( user=request.user, username=username, features=features, password_form=password_form, saved=saved, account_info=account_info, ))
def test_mcq_basic(self): """ Basic question template. Really the minimal possible example. NOTE: it would be much cleaner to have {{ a+b |quick_eval }} instead of {% quick_eval "a+b" %} unfortunately the former (a Django template filter) evaluates "a" and "b" directly and does not pass the context dictionary. The latter (a Django template tag) is far more powerful and gives us additional flexibility at render time. """ some_text = """ [[type]] MCQ [[question]] If a={{a}}, b={{b}}. What is a*b? -- & {{a}}{{b}} &1 ^{% quick_eval "a*b" 5 %} & {% quick_eval "a+b" 2 %} [[variables]] a: [2, 5, 0.5, float] b: [5, 9, 1, int] """ qtemplate = views.create_question_template(some_text, user=user) qt = QTemplate.objects.get(id=qtemplate.id) _, html_a, var_dict, _ = render(qt) true_answer = var_dict['a'][1] * var_dict['b'][1] self.assertEqual(html_a, '<p>The solution is: "%s"</p>' % true_answer)
def signin_view(): template_name = 'signin.html' if request_is_get(): return render(template_name) username = form_get('username') password = form_get('password') try: user = User.get(User.username == username, User.password == password, User.is_active == True) except: return render(template_name, message=_('username or password is an error')) signin(user) return render('redirect.html', url=URL['index'])
def test_tf_final_correct(self): """ Lures and an CORRECT option that must be shown as the last option. """ some_text = """ [[type]] TF [[question]] The sun is .... -- & Cold & Luke warm & Warm %^ None of the above. """ qtemplate = views.create_question_template(some_text, user=user) qt = QTemplate.objects.get(id=qtemplate.id) html_q, _, _, _ = render(qt) key, value = views.get_type(qt.t_grading, 'final-key').next() self.assertTrue(key.startswith('None of the above.')) start = html_q.find(value) self.assertEqual(html_q[start + 7:start + 11], 'None') self.assertEqual(qt.t_solution, ('The solution is: "None of the ' 'above."'))
def test_tf_basic(self): """ Basic true/false template. Really the minimal possible example. """ some_text = """ [[type]] TF [[question]] The sun is hot. -- & False ^True """ qtemplate = views.create_question_template(some_text, user=user) qt = QTemplate.objects.get(id=qtemplate.id) html_q, _, _, _ = render(qt) key, value = views.get_type(qt.t_grading, 'key').next() self.assertTrue(key.startswith('True')) start = html_q.find(value) self.assertEqual(html_q[start + 7:start + 11], 'True') key, value = views.get_type(qt.t_grading, 'lure').next() self.assertTrue(key.startswith('False')) start = html_q.find(value) self.assertEqual(html_q[start + 7:start + 12], 'False')
def offer_form_view(offer_type): template_name = 'offer_form.html' user = session_user() if user is None: return render('redirect.html', url=URL['offer']) cities = City.select() pet_categories = PetCategory.select() if request_is_get(): return render(template_name, cities=cities, pet_categories=pet_categories, offer_type=offer_type) for (id, name) in OFFER_TYPES.items(): if name == offer_type: offer_id = id break try: city = City.get(City.id == int(form_get('city'))) city_note = form_get('city_note', '') pet_category = PetCategory.get(PetCategory.id == int(form_get('pet_category', ''))) pet_category_note = form_get('pet_category_note', '') petname = form_get('petname', '') special = form_get('special', '') note = form_get('note', '') find_at = form_get('date', datetime.datetime.now()) except: return render(template_name, cities=cities, pet_categories=pet_categories, offer_type=offer_type) entry = Entry.create( user=user, type=offer_id, petcategory=pet_category, petcategory_note=pet_category_note, city=city, city_note=city_note, name=petname, special=special, note=note, find_at=datetime.datetime.strptime(find_at, '%Y-%m-%d %H:%M'), modified_at=datetime.datetime.now(), ) upload_images = request.files.getlist('images[]') upload_images_save('entry', upload_images, user, entry) return render('redirect.html', url=URL['search'])
def search_type_id_view(type_id, page=1): template_name = 'search_list.html' try: petcategory = PetCategory.get(PetCategory.id == type_id) except: abort(404) if request_is_get(): entries = Entry.select().where(Entry.petcategory == petcategory, Entry.is_active == True) return render(template_name, entries=entries.order_by(Entry.created_at.desc()), petcategory=petcategory, page=page)
def entry_view(entry_id): template_name = 'index.html' if Entry.select().where(Entry.id == entry_id, Entry.is_active == True, Entry.parent == None).exists(): entries = Entry.select().where(Entry.id == entry_id, Entry.is_active == True) responses = Entry.select().where(Entry.parent << entries) else: abort(404) return views.render(template_name, entries=entries, responses=responses, is_entry=True)
def mypage_view(page=1): template_name = 'mypage.html' user = session_user() if user is None: abort(404, _('access denied')) if request_is_get(): entries = Entry.select().where(Entry.user == user, Entry.is_active == True).order_by(Entry.created_at.desc()) return render(template_name, entries=entries, page=page)
def search(request): query_term = "" for term in request.GET['q']: query_term += term results = \ get_search_results( 'YLPjx2rV34F4hXcTnJYqYJUj9tANeqax76Ip2vADl9kKuByRNHgC4qafbATFoQ', query_term, site=site) print [result['Url'] for result in results] payload = {'results': results} return views.render('search.html', request, payload)
def create_featured (request): if not request.user.is_staff: return HttpResponseForbidden() if request.method == 'POST': featured_page_form = forms.MakeFeatured(request.POST) if featured_page_form.is_valid(): featured_page_form.save() return HttpResponseRedirect('.') elif request.method == 'GET': featured_page_form = forms.MakeFeatured() payload = {'form':featured_page_form} return render(request, 'djikiki/edit.html', payload)
def contact_view(): template_name = 'contact.html' if request_is_get(): return render(template_name) name = form_get('name') from_address = form_get('email') body = form_get('body', '') agree = form_get('cb', False) if not agree: return render(template_name, message=_('Please agree')) if not name or not from_address: return render(template_name, message=_('has not been entered')) send = mail_send(from_address=from_address, subject=_('Was accepted - example.jp'), body="%s\n\n%s" % (name, body)) if not send: return render(template_name, message=_('An error has occurred')) return render(template_name, message=_('Has been sent'))
def signup_view(): template_name = 'signup.html' if request_is_get(): return render(template_name) username = form_get('username') password = form_get('password') email = form_get('email') agree = request.forms.get('cb', False) if not agree: return render(template_name, message=_('Please agree')) if not (username.isalnum() and password.isalnum()): return render(template_name, message=_('Username and Password is alphabet or num')) if User.select().where(User.username == username, User.password == password).count(): return render(template_name, message=_('User exist')) if not (len(username) >= LENGTH['username'] and len(password) >= LENGTH['password']): return render(template_name, message=_('Username or Password not enough')) user = User.create( username=username, password=password, password_hash=hashlib.sha256(password.encode()).hexdigest(), email=email ) UserProfile.create( user=user ) signin(user) return render('redirect.html', url=URL['setting'])
def user_view(user_id, page=1): template_name = 'user.html' try: page_user = User.get(User.id == user_id, User.is_active == True) page_user_profile = UserProfile.get(UserProfile.user == page_user) except: abort(404) if request_is_get(): page_user_images = UserProfile_Image.select().where(UserProfile_Image.user == page_user, UserProfile_Image.is_active == True) entries = Entry.select().where(Entry.user == page_user, Entry.is_active == True).order_by(Entry.created_at.desc()) return render(template_name, page_user=page_user, page_user_profile=page_user_profile, entries=entries, page_user_images=page_user_images, page=page)
def test_peer_evaluation(self): """ Template for peer evaluation. """ some_text = """ [[type]] Peer-eval [[question]] * Name one aspect of {{person}}'s work that you really appreciated this week: {[[person_slug_positive]]} * Provide constructive feedback on {{person}}'s work that will help him/her improve. {[[person_slug_feedback]]} * Please rank {{person}}'s contribution to the assignment: --ranking-- Note: your evaluation for each person will be a number from 0 to 8, with 6 being typical, satisfactory performance. + 0 = No show = Made no contribution. I could not recognize this person in a lineup. + 2 = Hitchhiker = Made minimal contribution. The group could have received the same grade without this member. + 4 = Marginal = Made limited contribution, only when required to do so. Took no initiative, was not always prepared and missed meetings. + 5 = Ordinary = Performed some tasks acceptably but was not reliable or consistent. + 6 = Fully satisfactory = Made good contributions to work and group organization and morale. This is the average performance for a student in the course. + 7 = Very good = Consistently showed initiative and preparation beyond expectations. High quality of work. + 8 = Excellent = Lead the group by example and personality. Prepared excellent technical work and assisted others to excel. [[attribs]] Name: Peer feedback for Assignment 1 (on personal finance) Contributor: Kevin Dunn Difficulty: 1 Grade: 1 Feedback: False """ group = Group.objects.create(name='TestA1') user_2 = User.objects.create(username='******', first_name='Test', last_name='user2') user_2 = UserProfile.objects.create(role='Grader', group=group, user=user_2) user_3 = User.objects.create(username='******', first_name='Test', last_name='user3') user_3 = UserProfile.objects.create(role='Grader', group=group, user=user_3) user.group = group user.save() qtemplate = views.create_question_template(some_text, user=user) qt = QTemplate.objects.get(id=qtemplate.id) options = {} options['peers'] = user.get_peers() html_q, html_a, var_dict, _ = render(qt, options)
def search_from_view(offer_type='full', page=1): template_name = 'search_list.html' for (id, name) in OFFER_TYPES.items(): if name == offer_type: offer_id = id break if request_is_get(): if offer_id == 9: entries = Entry.select().where(Entry.is_active == True) else: entries = Entry.select().where(Entry.type == offer_id, Entry.is_active == True) return render(template_name, entries=entries.order_by(Entry.created_at.desc()), page=page, offer_type=offer_type)
def test_question_missing_variable(self): some_text = """ [[type]] multi [[question]] Our process produces defective products at a rate of 1 in {{n_total}}. If we randomly take a sample of {{n_sample}} items from the production line,then .... -- ^{% quick_eval "((n_total-1)/n_total)**n_sample" %} & {% quick_eval "((n_total-1)/n_total)" %} & be greater than or equal to ({{n_total}}-1)/{{n_total}}) & is equal to 1/{{n_total}} [[variables]] n_total: [6, 10, 1, int] n: [4,6,1,int] [[Solution]] The pass rate for this system is ({{n_total}}-1)/{{n_total}}), so """ # The ``n_sample`` variable is not specified qtemplate = views.create_question_template(some_text, user=user) qt = QTemplate.objects.get(id=qtemplate.id) with self.assertRaises(NameError): render(qt)
def search_city_id_view(city_id, page=1): template_name = 'search_list.html' try: city = City.get(City.id == city_id) if city.parent is not None: city = city.parent except: abort(404) if request_is_get(): entries = Entry.select().join(City).where(((Entry.city == city)|(City.parent == city)), Entry.is_active == True) print('---') print(entries.count()) return render(template_name, entries=entries.order_by(Entry.created_at.desc()), city=city, page=page)
def install (request): if not request.user.is_staff: return HttpResponseForbidden() if request.method == 'POST' : install_form = forms.InstallForm(request.POST) if install_form.is_valid(): install_form.save() return HttpResponseRedirect('/') elif request.method == 'GET': install_form = forms.InstallForm() payload = {'form':install_form} return render(request, 'djikiki/edit.html', payload)
def test_variables_with_choices(self): some_text = """ [[type]] long [[question]] Plot a time series plot using rows {{row_start}} to {% quick_eval "row_start+1000" %} for the `{{variable_name}}` variable. Save the plot as a JPEG or PNG file and upload it here {[:upload:]} [[variables]] row_start:[1, 2000, 100, int] variable_name: {'choices': ['Opt1', 'Opt2', 'Opt3']} [[solution]] Some solution text would go here. [[grading]] """ qtemplate = views.create_question_template(some_text, user=user) qt = QTemplate.objects.get(id=qtemplate.id) html_q, _, _, _ = render(qt) start = html_q.find('for the <code>') self.assertTrue(html_q[start + 14:start + 18] in ('Opt1', 'Opt2', 'Opt3'))
def test_image_location(self): """ Tests that images are placed in the correct location """ some_text = """ [[type]] TF [[question]] The image here contains oscillations ![Image alt text](image_file_name.jpg) -- & False ^ True """ qtemplate = views.create_question_template(some_text, user=user) qt = QTemplate.objects.get(id=qtemplate.id) html_q, _, _, _ = render(qt) idx = html_q.find('image_file_name.jpg') self.assertEqual(html_q[idx - 3:idx], '/0/') # this is the subdir stored in
def test_short_answer_question(self): """ Template test for a short answer question """ some_text = """ [[type]] short [[question]] Plots with both category and value axes are known as {[ans1]} plots, while a plot with the 5-number summary of a univariate series are called {[2]} plots. [[grading]] ans1:bar ans1:BAR 2:box [[solution]] Goes here [[attribs]] Contributor: Kevin Dunn Difficulty: 1 Tags: data visualization Grade: 1 """ qtemplate = views.create_question_template(some_text, user=user) qt = QTemplate.objects.get(id=qtemplate.id) self.assertEqual(qt.t_solution, u'Goes here') t_grading = json.loads(qt.t_grading) vals = t_grading.values() keys = t_grading.keys() self.assertEqual(keys, ['ans1', '2']) # <--- keys are strings self.assertEqual(vals, [['bar', 'BAR'], ['box']]) html_q, _, _, _ = render(qt) self.assertEqual(html_q[0:74], ('<p>Plots with both category ' 'and value axes are known as <input type="text"'))
def signout_view(): signout() return render('redirect.html', url=URL['index'])
def server_error(error): if request.is_xhr: return render_json(u'出错了...') return render("errors/500.html", error=error)
import views site = 'blogango.com' def search(request): query_term = "" for term in request.GET['q']: query_term += term results = \ get_search_results( 'YLPjx2rV34F4hXcTnJYqYJUj9tANeqax76Ip2vADl9kKuByRNHgC4qafbATFoQ', query_term, site=site) print [result['Url'] for result in results] payload = {'results': results} return views.render('search.html', request, payload) def get_search_results(appid, query, region='us', type='all', results=10, start=0, format='any', adult_ok="", similar_ok="", language="", country="", site="", subscription="", license=''): base_url = u'http://search.yahooapis.com/WebSearchService/V1/webSearch?' params = locals() result = _query_yahoo(base_url, params) return result['ResultSet']['Result'] def _query_yahoo(base_url, params): params['output'] = 'json' payload = urllib.urlencode(params)
def error500(error): return views.render("500.html")
def index_view(): template_name = 'index.html' entries = Entry.select().where(Entry.parent == None, Entry.is_active == True) return views.render(template_name, entries=entries, is_index=True)
def render(self, context, instance, placeholder): return render(context, instance, placeholder)
def error404(error): return views.render("404.html")
def edit_view(entry_id): template_name = 'edit.html' user = session_user() if user is None: abort(404, _('access denied')) try: entry = Entry.get(Entry.user == user, Entry.id == entry_id, Entry.is_active == True) except: abort(404) cities = City.select() pet_categories = PetCategory.select() entry_images = Entry_Image.select().where(Entry_Image.user == user, Entry_Image.entry == entry, Entry_Image.is_active == True) if request_is_get(): return render(template_name, entry=entry, entry_images=entry_images, cities=cities, pet_categories=pet_categories) if form_get('remove-image'): remove_image_id = form_get('image_id') try: image = Entry_Image.get(Entry_Image.user == user, Entry_Image.id == remove_image_id) except: abort(404) image.is_active = False image.save() return render('redirect.html', url='') if form_get('close'): close_entry_id = form_get('entry_id') agree = form_get('cb', False) if not agree: return render('redirect.html', url='') try: entry = Entry.get(Entry.user == user, Entry.id == close_entry_id) except: abort(404) entry.is_open = False entry.save() return render('redirect.html', url=URL['mypage']) try: city = City.get(City.id == int(form_get('city'))) city_note = form_get('city_note', '') pet_category = PetCategory.get(PetCategory.id == int(form_get('pet_category', ''))) pet_category_note = form_get('pet_category_note', '') petname = form_get('petname', '') special = form_get('special', '') note = form_get('note', '') find_at = form_get('date', datetime.datetime.now()) except: return render(template_name, entry=entry, entry_images=entry_images, cities=cities, pet_categories=pet_categories) entry.petcategory = pet_category entry.petcategory_note = pet_category_note entry.city = city entry.city_note = city_note entry.name = petname entry.special = special entry.note = note entry.find_at = datetime.datetime.strptime(find_at, '%Y-%m-%d %H:%M') entry.modified_at = datetime.datetime.now() entry.save() upload_images = request.files.getlist('images[]') upload_images_save('entry', upload_images, user, entry) return render('redirect.html', url=URL['search_entry'].replace('<entry_id:int>', str(entry.id)))
def controller(env): '''Main controller for the application''' if env.get('REQUEST_METHOD') == 'GET': # get the template template = get_template() # Default search location locations = db.get_locations() location_html = locations_to_html(locations) name = 'New York' lon = 73.935242 lat = 40.730610 # get raw json my_json = get_api(lon, lat) # convert json to html str html_images = json_to_html(my_json) return render( template, { 'photos': html_images, 'lon': lon, 'lat': lat, 'name': name, 'options': location_html }) elif env.get('REQUEST_METHOD') == 'POST': # get POST Data try: r_body_size = int(env.get('CONTENT_LENGTH', 0)) except (ValueError): r_body_size = 0 # get template template = get_template() d = env['wsgi.input'].read(r_body_size) data = parse_qs(d) lon = float(data.get(b'lon', [])[0]) lat = float(data.get(b'lat', [])[0]) try: name = (data.get(b'location-name', [])[0]).decode('utf-8') except: name = 'Mystery location' if b'pre-location-search' in data: loc_id = int(data.get(b'location-select', [])[0]) print(loc_id) loc = db.get_location(loc_id) print(loc) name = loc[0][1] lon = loc[0][2] lat = loc[0][3] if b'location-save' in data: db.save_location(name, lon, lat) locations = db.get_locations() location_html = locations_to_html(locations) # get json data my_json = get_api(lon, lat) html_images = json_to_html(my_json) return render( template, { 'photos': html_images, 'lon': lon, 'lat': lat, 'name': name, 'options': location_html })
def error500(err): return render('500.html', error=err)
def index_view(): template_name = 'index.html' return render(template_name)
def error404(err): return render('404.html', error=err)
def offer_view(): template_name = 'offer.html' return render(template_name)
def account_view(): template_name = 'account.html' return render(template_name)
def search_city_view(): template_name = 'search_city.html' if request_is_get(): cities = City.select().where(City.parent == None) return render(template_name, cities=cities)
def search_type_view(): template_name = 'search_type.html' if request_is_get(): petcategories = PetCategory.select() return render(template_name, petcategories=petcategories)