def concept_save_view(request): if "concept" in request.POST: form = Form(request, schema=ConceptAnswersSchema()) if form.validate(): answers = [] concept_answers = form.bind(models.ConceptAnswer()) concept = concept_answers.concept concept_answers = concept_answers.concept_answer for concept_answer in concept_answers: answer = models.ConceptAnswer() answer.concept = concept answer.concept_answer = concept_answer answers.append(answer) with transaction.manager: models.DBSession.add_all(answers) else: print form.all_errors() print "NOT VALIDATED" return "I saw it" form = Form(request, schema=ConceptSchema()) concept_model = None if form.validate(): concept = form.bind(models.Concept()) #with transaction.manager: # models.DBSession.add(concept) concept_model = models.DBSession.merge(concept) models.DBSession.flush() return HTTPFound(request.route_url("concept_edit_page", page="Concepts",\ concept_id=concept_model.id)) else: print "Failed"
def health_unit_type_save_view(request): form = Form(request, schema=HealthUnitTypeSchema()) if form.validate(): health_unit_type = form.bind(models.HealthUnitType()) with transaction.manager: models.DBSession.add(health_unit_type) return exc.HTTPFound(request.route_url("health_unit_type_list", \ page="Health Unit Types", headings= headings)) else: print "Validation Failed!!!!" print form.all_errors()
def addpurchaselineitem(self): purchaseId = self.request.params.get('pid', None) supplierId = self.request.params.get('SupplierId', None) if purchaseId and supplierId: model = None productId = self.request.params.get('ProductId', None) quantity = float(self.request.params.get('Quantity', 0.0)) taxAmount = float(self.request.params.get('TaxAmount', 0.0)) try: if productId: model = stockService.GetProduct(productId, self.TenantId) if not model: model = Product() pForm = Form(self.request, schema=ProductSchema, obj=model) if pForm.validate(): pForm.bind(model) model.SupplierId = supplierId model.TenantId = self.TenantId model.Status = True if model.Id: model.UpdatedBy = self.UserId stockService.SaveProduct(model) else: model.CreatedBy = self.UserId stockService.AddProduct(model) litem = PurchaseLineItem() litem.PurchaseId = purchaseId litem.ProductId = model.Id litem.Name = model.Name litem.Barcode = model.Barcode litem.MRP = model.MRP litem.Tax = taxAmount litem.BuyPrice = model.BuyPrice litem.Discount = model.Discount litem.Quantity = quantity result = stockService.AddPurchaseLineItem(litem, self.TenantId) if result: return dict(status=True, id=litem.Id, message="Item added successfully!") else: DBSession.rollback() else: log.info('pForm validate failed : %s!' % (pForm.all_errors())) return dict(status=False, message=pForm.all_errors()) except Exception, e: log.debug(e) DBSession.rollback() return dict(status=False, message=e.message)
def location_add(request): form = Form(request, schema=LocationSchema()) if form.validate(): location = form.bind(models.Location()) with transaction.manager: models.DBSession.add(location) locations = models.DBSession.query(models.Location).all() locations_list = [(location.id, location.name) for location in locations] return {"page": "Locations", "items": locations_list, "headings": headings} else: print form.all_errors() print form.errors_for('parent') print "Form validation failed"
def person_relation_save_view(request): health_id = request.matchdict["health_id"] print request.params.mixed() person_a = request.params['person_a'] person_b = request.params['person_b'] form = Form(request, RelationshipSchema()) if form.validate(): relationship = form.bind(models.Relationship()) with transaction.manager: models.DBSession.add(relationship) return HTTPFound(request.route_url("patient_dashboard_page", health_id=person_a)) else: print form.all_errors()
def promo_sub(request): id = request.matchdict['id'] user = Users.get_by_id(id) if not user: return HTTPNotFound() form = Form(request, schema=PromoSubSchema) if 'submit' in request.POST and form.validate(): plan_id = form.data['plan'] plan = DBSession.query(Plans).get(plan_id) if plan: subscription = Subscription(user=user, plan=plan, amount=0, no_of_months=1, discount="100%", status="Active", start_date=datetime.today(), end_date=datetime.today() + timedelta(days=30)) DBSession.add(subscription) DBSession.flush() if request.is_xhr: html = """<div class="alert alert-success alert-dismissable col-xs-12"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> User subscription </div>""" return Response(html) request.session.flash('success; User subscribed') return HTTPFound( location=request.route_url('profile', prefix=user.prefix)) if request.is_xhr: html = """<div class="alert alert-danger alert-dismissable col-xs-12"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> An error occured, user Not subscribed </div>""" return Response(html) request.session.flash('danger; An error occured, user subscribed %s' % form.all_errors()) return HTTPFound( location=request.route_url('profile', prefix=user.prefix)) if request.is_xhr: html = """<div class="alert alert-danger alert-dismissable col-xs-12"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> An error occured, user Not subscribed </div>""" return Response(html) request.session.flash('danger; An error occured, user subscribed %s' % form.all_errors()) return HTTPFound(location=request.route_url('profile', prefix=user.prefix))
def person_relation_save_view(request): health_id = request.matchdict["health_id"] print request.params.mixed() person_a = request.params['person_a'] person_b = request.params['person_b'] form = Form(request, RelationshipSchema()) if form.validate(): relationship = form.bind(models.Relationship()) with transaction.manager: models.DBSession.add(relationship) return HTTPFound( request.route_url("patient_dashboard_page", health_id=person_a)) else: print form.all_errors()
def person_add_view(request): health_id = request.POST['health_id'] form = Form(request, schema=PersonSchema()) if form.validate(): person = form.bind(models.Person()) with transaction.manager: models.DBSession.add(person) return HTTPFound(request.route_url("patient_dashboard_page",\ health_id=health_id, page= "Patient Dashboard")) #page= "Patients List", health_id= health_id) else: print "Form Validation Failed" print form.all_errors() print request.POST return {"message": "Reched ME!!"}
def location_add(request): form = Form(request, schema=LocationSchema()) if form.validate(): location = form.bind(models.Location()) with transaction.manager: models.DBSession.add(location) locations = models.DBSession.query(models.Location).all() locations_list = [(location.id, location.name) for location in locations] return { "page": "Locations", "items": locations_list, "headings": headings } else: print form.all_errors() print form.errors_for('parent') print "Form validation failed"
def form_save(request): form_id = request.params["form", None] if form_id: form = Form(request, schema=FormConceptSchema()) if form.validate(): concepts = [] form_concepts = form.bind(models.FormConcept()) form_id = form_concepts.form form_concepts = form_concepts.concepts for form_concept in form_concepts: concept = models.FormConcept() concept.form = form_id concept.concept = form_concept concepts.append(concept) with transaction.manager: models.DBSession.add_all(concepts) return HTTPFound(request.route_url("form_list", page="List of Forms", \ items=get_forms(), headings=headings)) else: print "validation_failed" print form.all_errors() print request.params return else: print "We are dealing with a new form" form = Form(request, schema=FormSchema) if form.validate(): form_model = form.bind(models.Form()) #with transaction.manager: # models.DBSession.merge(form_model) form_model = models.DBSession.merge(form_model) models.DBSession.flush() print form_model.id return HTTPFound(request.route_url(\ "form_edit_page", page="Forms", form_id=form_model.id,\ form=FormRenderer(form))) else: print "validation Failed!!!"
def login_view(request): """ Perform a 'login' by getting the service document from a sword repository. """ templatePath = 'templates/login.pt' config = load_config(request) form = Form(request, schema=LoginSchema) field_list = [ ('username', ), ('password', ), ] session = request.session # validate the form in order to compute all errors valid_form = form.validate() request['errors'] = form.all_errors() # Check for successful form completion if 'form.submitted' in request.POST and valid_form: if form.data['anonymous']: login = AnonymousSession() else: login = auth(form.data['service_document_url'], form.data['username'], form.data['password']) if login is None: request['errors'] = [ "Invalid username or password. Please try again.", ] response = { 'form': FormRenderer(form), 'field_list': field_list, 'config': config, } return render_to_response(templatePath, response, request=request) # The login details are persisted on the session. if TESTING: session['login'] = TestingSession() else: session['login'] = login return HTTPFound(location=request.route_url('choose')) elif 'login' in session: return HTTPFound(location=request.route_url('choose')) # If not signed in, go to login page response = { 'form': FormRenderer(form), 'field_list': field_list, 'config': config, } return render_to_response(templatePath, response, request=request)
def test_all_errors_with_list(self): from pyramid_simpleform import Form request = testing.DummyRequest() request.method = "POST" form = Form(request, SimpleFESchema) form.errors = [u"Name is missing"] self.assert_(form.all_errors() == [u"Name is missing"])
def test_all_errors_with_dict(self): from pyramid_simpleform import Form request = testing.DummyRequest() request.method = "POST" form = Form(request, SimpleFESchema) form.errors = {"name": [u"Name is missing"], "value": u"Value is missing"} self.assert_(sorted(form.all_errors()) == sorted([u"Name is missing", u"Value is missing"]))
def health_unit_add(request): form = Form(request, schema=HealthUnitSchema()) health_unit_id = None if form.validate(): health_unit = form.bind(models.HealthUnit()) h_unit = None #with transaction.manager: #location = models.DBSession.query(models.Location).get(health_unit.location) #unit_type = models.DBSession.query(models.HealthUnitType).get(health_unit.health_unit_type_id) #health_unit.location = location #health_unit.health_unit_type_id = unit_type h_unit = models.DBSession.merge(health_unit) models.DBSession.flush() models.DBSession.close() health_unit_id = h_unit.id print "HEALTH UNIT ID: ", health_unit_id health_units = models.DBSession.query(models.HealthUnit).all() units = [(health_unit.id, health_unit.name) for health_unit in health_units] return exc.HTTPFound(request.route_url("health_unit_dashboard", health_unit_id=health_unit_id,page="Health Units", items=units, headings=health_unit_headings)) else: print form.all_errors() return "Failed"
def test_error_with_jsonbody(self): from pyramid_simpleform import Form request = testing.DummyRequest() request.method = "POST" import json request.json_body = json.loads("{}") form = Form(request, SimpleFESchema) form.errors = {"name": [u"Name is missing"], "value": u"Value is missing"} self.assert_(sorted(form.all_errors()) == sorted([u"Name is missing", u"Value is missing"]))
def test_all_errors_with_dict(self): from pyramid_simpleform import Form request = testing.DummyRequest() request.method = "POST" form = Form(request, SimpleFESchema) form.errors = { "name": [u"Name is missing"], "value": u"Value is missing" } self.assert_( sorted(form.all_errors()) == sorted( [u"Name is missing", u"Value is missing"]))
def test_error_with_jsonbody(self): from pyramid_simpleform import Form request = testing.DummyRequest() request.method = "POST" import json request.json_body = json.loads('{}') form = Form(request, SimpleFESchema) form.errors = { "name": [u"Name is missing"], "value": u"Value is missing" } self.assert_( sorted(form.all_errors()) == sorted( [u"Name is missing", u"Value is missing"]))
def process_lipisha_payment(request): """Handle payment received and respond with a dictionary""" log.debug(request.POST) schema = LipishaInitiateSchema api_type = request.POST.get('api_type') if api_type == TYPE_ACKNOWLEDGE: schema = LipishaAcknowledgeSchema form = Form(request, schema()) transaction_status_code = STATUS_SUCCESS transaction_status = 'Processed' transaction_status_description = 'Processed' if form.validate(): if api_type == TYPE_INITIATE: # Process new payment pass elif api_type == TYPE_ACKNOWLEDGE: if form.data.get('transaction_status_code') == STATUS_SUCCESS: # Process successful accknowledgement pass else: log.error('Invalid payment acknowledgement') log.error(request.POST) else: log.error("Error while processing payment") for error in form.all_errors(): log.error(error) transaction_status_code = STATUS_INITIATE_FAILURE transaction_status = 'Error' transaction_status_description = 'Error while processing' if api_type == TYPE_INITIATE: data = request.POST return dict( api_key=LIPISHA_API_KEY, api_signature=LIPISHA_API_SIGNATURE, api_version=data.get('api_version'), api_type=TYPE_RECEIPT, transaction_reference=data.get('transaction_reference'), transaction_status_code=transaction_status_code, transaction_status=transaction_status, transaction_status_description=transaction_status_description, ) return {}
def login_view(request): """ Perform a 'login' by getting the service document from a sword repository. """ templatePath = "templates/login.pt" config = load_config(request) form = Form(request, schema=LoginSchema) field_list = [("username",), ("password",)] session = request.session # validate the form in order to compute all errors valid_form = form.validate() request["errors"] = form.all_errors() # Check for successful form completion if "form.submitted" in request.POST and valid_form: if form.data["anonymous"]: login = AnonymousSession() else: login = auth(form.data["service_document_url"], form.data["username"], form.data["password"]) if login is None: request["errors"] = ["Invalid username or password. Please try again."] response = {"form": FormRenderer(form), "field_list": field_list, "config": config} return render_to_response(templatePath, response, request=request) # The login details are persisted on the session. if TESTING: session["login"] = TestingSession() else: session["login"] = login return HTTPFound(location=request.route_url("choose")) elif "login" in session: return HTTPFound(location=request.route_url("choose")) # If not signed in, go to login page response = {"form": FormRenderer(form), "field_list": field_list, "config": config} return render_to_response(templatePath, response, request=request)
def navigate(self, errors=None, form=None): request = self.request neworexisting_form = Form(request, schema=NewOrExistingSchema) officedocument_form = Form(request, schema=OfficeDocumentUploadSchema) googledocs_form = Form(request, schema=GoogleDocsSchema) url_form = Form(request, schema=URLSchema) presentationform = Form(request, schema=PresentationSchema) zip_or_latex_form = Form(request, schema=ZipOrLatexSchema) LOG.info(presentationform.all_errors()) #TODO: This can be replaced by utility/adapter lookups # Check for successful form completion if neworexisting_form.validate(): return self._process_neworexisting_submit(request, neworexisting_form) elif officedocument_form.validate(): return self._process_officedocument_submit(request, officedocument_form) elif googledocs_form.validate(): return self._process_googledocs_submit(request, googledocs_form) elif url_form.validate(): return self._process_url_submit(request, url_form) elif presentationform.validate(): return self._process_presentationform_submit( request, presentationform) elif zip_or_latex_form.validate(): return self._process_zip_or_latex_form(request, zip_or_latex_form) templatePath = 'templates/choose.pt' # First view or errors response = { 'neworexisting_form': FormRenderer(neworexisting_form), 'officedocument_form': FormRenderer(officedocument_form), 'googledocs_form': FormRenderer(googledocs_form), 'url_form': FormRenderer(url_form), 'presentationform': FormRenderer(presentationform), 'zip_or_latex_form': FormRenderer(zip_or_latex_form), 'view': self, } return render_to_response(templatePath, response, request=self.request)
def navigate(self, errors=None, form=None): request = self.request neworexisting_form = Form(request, schema=NewOrExistingSchema) officedocument_form = Form(request, schema=OfficeDocumentUploadSchema) googledocs_form = Form(request, schema=GoogleDocsSchema) url_form = Form(request, schema=URLSchema) presentationform = Form(request, schema=PresentationSchema) zip_or_latex_form = Form(request, schema=ZipOrLatexSchema) LOG.info(presentationform.all_errors()) #TODO: This can be replaced by utility/adapter lookups # Check for successful form completion if neworexisting_form.validate(): return self._process_neworexisting_submit(request, neworexisting_form) elif officedocument_form.validate(): return self._process_officedocument_submit(request, officedocument_form) elif googledocs_form.validate(): return self._process_googledocs_submit(request, googledocs_form) elif url_form.validate(): return self._process_url_submit(request, url_form) elif presentationform.validate(): return self._process_presentationform_submit(request, presentationform) elif zip_or_latex_form.validate(): return self._process_zip_or_latex_form(request, zip_or_latex_form) templatePath = 'templates/choose.pt' # First view or errors response = { 'neworexisting_form': FormRenderer(neworexisting_form), 'officedocument_form': FormRenderer(officedocument_form), 'googledocs_form': FormRenderer(googledocs_form), 'url_form': FormRenderer(url_form), 'presentationform': FormRenderer(presentationform), 'zip_or_latex_form': FormRenderer(zip_or_latex_form), 'view': self, } return render_to_response(templatePath, response, request=self.request)
def email_passw(request): user = request.user form = Form(request, schema=ChangeEmailPassword, obj=user) if 'pass_submitted' in request.POST and form.validate(): form.bind(user) DBSession.add(user) DBSession.flush() if request.is_xhr: html = """<div class="alert alert-success alert-dismissable col-xs-12"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> Update Successful </div>""" return Response(html) request.session.flash("success; Email and password saved") return HTTPFound(location=request.route_url('account')) if request.is_xhr: html = """<div class="alert alert-danger alert-dismissable col-xs-12"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> Update not Successful {0} </div>""".format(form.all_errors()) return Response(html) request.session.flash("danger; Update not successful") return HTTPFound(location=request.route_url('account'))
def enhance(request): check_login(request) session = request.session google_resource_id = "" slideshare_id = "" embed_google = False embed_slideshare = False not_converted = True show_iframe = False form = Form(request, schema=QuestionAnswerSchema) validate_form = form.validate() print form.all_errors() if session.has_key('google-resource-id'): google_resource_id = session['google-resource-id'] if session.has_key('slideshare_id'): slideshare_id = session['slideshare_id'] if fetch_slideshow_status(slideshare_id) == "2": not_converted = False show_iframe = True if google_resource_id != "": embed_google = True if slideshare_id != "": embed_slideshare = True templatePath = "templates/google_ss_preview.pt" if validate_form: introductory_paragraphs = request.POST.get('introductory_paragraphs') question_count = 0 cnxml = session[ "cnxml"] + """<content><section id="intro-section-title"><title id="introtitle">Introduction</title><para id="introduction-1">""" + introductory_paragraphs + """</para></section><section id="slides-embed"><title id="slide-embed-title">View the slides</title><figure id="ss-embed-figure"><media id="slideshare-embed" alt="slideshare-embed"><iframe src="http://www.slideshare.net/slideshow/embed_code/""" + slideshare_id + """" width="425" height="355" /></media></figure></section>""" for i in range(1, 6): form_question = request.POST.get('question-' + str(i)) if form_question: form_radio_answer = request.POST.get( 'radio-' + str(i) ) #this give us something like 'answer-1-1'. so our solution is this question_count += 1 if question_count == 1: cnxml += """<section id="test-section"><title>Test your knowledge</title>""" itemlist = "" for j in range(1, 10): try: form_all_answers = request.POST.get('answer-' + str(i) + '-' + str(j)) if form_all_answers: itemlist += "<item>" + form_all_answers + "</item>" except: print "No element found" if form_radio_answer: solution = request.POST.get(form_radio_answer) cnxml += """<exercise id="exercise-""" + str( i ) + """"><problem id="problem-""" + str( i ) + """"><para id="para-""" + str(i) + """">""" + str( form_question ) + """<list id="option-list-""" + str( i ) + """" list-type="enumerated" number-style="lower-alpha">""" + str( itemlist) + """</list></para></problem>""" else: print "ELESE CONDUITION OF radio" solution = request.POST.get('answer-' + str(i) + '-1') cnxml += """<exercise id="exercise-""" + str( i) + """"><problem id="problem-""" + str( i) + """"><para id="para-""" + str( i) + """">""" + str( form_question) + """</para></problem>""" print "FORM RADIO ANSWER", form_radio_answer print "SOLUTION", solution cnxml += """ <solution id="solution-""" + str( i ) + """"> <para id="solution-para-""" + str( i ) + """">""" + solution + """</para></solution></exercise>""" """form_solution = request.POST.get('solution-'+str(i)) all_post_data = {"data":{"options":form_options,"solution":form_solution,"question":form_question}} for question in all_post_data: options = all_post_data[question]['options'] solution = all_post_data[question]['solution'] asked_question = all_post_data[question]['question'] optionlist="" for option in options: optionlist+="<item>"+option+"</item>""" #cnxml+="""<exercise id="exercise-"""+str(j)+""""><problem id="problem-"""+str(j)+""""><para id="para-"""+str(j)+"""">"""+str(asked_question)+"""<list id="option-list-"""+str(j)+"""" list-type="enumerated" number-style="lower-alpha">"""+str(optionlist)+"""</list></para></problem>""" #cnxml+=""" <solution id="solution-"""+str(j)+""""> <para id="solution-para-"""+str(j)+"""">"""+solution+"""</para></solution></exercise>""" #j+=1 metadata = session['metadata'] if question_count >= 1: cnxml += "</section></content></document>" else: cnxml += "</content></document>" workspaces = [(i['href'], i['title']) for i in session['login'].collections] metadata_entry = sword2cnx.MetaData(metadata) zipped_filepath = session['userfilepath'] zip_archive = zipfile.ZipFile(zipped_filepath, 'w') zip_archive.writestr("index.cnxml", cnxml) zip_archive.close() conn = sword2cnx.Connection("http://cnx.org/sword/servicedocument", user_name=session['login'].username, user_pass=session['login'].password, always_authenticate=True, download_service_document=True) collections = [{ 'title': i.title, 'href': i.href } for i in sword2cnx.get_workspaces(conn)] session['login'].collections = collections workspaces = [(i['href'], i['title']) for i in session['login'].collections] session['workspaces'] = workspaces with open(zipped_filepath, 'rb') as zip_file: deposit_receipt = conn.create( col_iri=workspaces[0][0], metadata_entry=metadata_entry, payload=zip_file, filename='upload.zip', mimetype='application/zip', packaging='http://purl.org/net/sword/package/SimpleZip', in_progress=True) session['dr'] = deposit_receipt session['deposit_receipt'] = deposit_receipt.to_xml() soup = BeautifulSoup(deposit_receipt.to_xml()) data = soup.find("link", rel="edit") edit_iri = data['href'] session['edit_iri'] = edit_iri creator = soup.find('dcterms:creator') username = session['login'].username email = creator["oerdc:email"] url = "http://connexions-oerpub.appspot.com/" post_values = { "username": username, "email": email, "slideshow_id": slideshare_id } data = urllib.urlencode(post_values) google_req = urllib2.Request(url, data) google_response = urllib2.urlopen(google_req) now_string = datetime.datetime.now().strftime('%Y%m%d-%H%M%S') temp_dir_name = '%s-%s' % (request.session['login'].username, now_string) save_dir = os.path.join(request.registry.settings['transform_dir'], temp_dir_name) os.mkdir(save_dir) request.session['upload_dir'] = temp_dir_name cnxml = clean_cnxml(cnxml) save_cnxml(save_dir, cnxml, []) return HTTPFound(location=request.route_url('metadata')) #return HTTPFound(location=request.route_url('updatecnx')) response = { 'form': FormRenderer(form), "slideshare_id": slideshare_id, "google_resource_id": google_resource_id, "embed_google": embed_google, "embed_slideshare": embed_slideshare, "not_converted": not_converted, "show_iframe": show_iframe } return render_to_response(templatePath, response, request=request)
def login_view(request): """ Perform a 'login' by getting the service document from a sword repository. """ templatePath = 'templates/login.pt' config = load_config(request) form = Form(request, schema=LoginSchema) field_list = [ ('username',), ('password',), ] session = request.session # validate the form in order to compute all errors valid_form = form.validate() request['errors'] = form.all_errors() # Check for successful form completion if 'form.submitted' in request.POST and valid_form: # The login details are persisted on the session for field_name in [i[0] for i in field_list]: session[field_name] = form.data[field_name] session['service_document_url'] = form.data['service_document_url'] loggedIn = True # Check if user is already authenticated else: loggedIn = True for key in ['username', 'password', 'service_document_url', 'collections', 'workspace_title', 'sword_version', 'maxuploadsize']: if not session.has_key(key): loggedIn = False if loggedIn: return HTTPFound(location=request.route_url('choose')) # TODO: check credentials against Connexions and ask for login # again if failed. # If not signed in, go to login page if not loggedIn: response = { 'form': FormRenderer(form), 'field_list': field_list, 'config': config, } return render_to_response(templatePath, response, request=request) # Here we know that the user is authenticated and that they did so # by logging in (rather than having had a cookie set already) if TESTING: session['workspace_title'] = "Connexions" session['sword_version'] = "2.0" session['maxuploadsize'] = "60000" session['collections'] = [{'title': 'Personal Workspace', 'href': 'http://'}] else: # Get the service document and persist what's needed. conn = sword2cnx.Connection(session['service_document_url'], user_name=session['username'], user_pass=session['password'], always_authenticate=True, download_service_document=True) try: # Get available collections from SWORD service document # We create a list of dictionaries, otherwise we'll have problems # pickling them. if not conn.sd.valid: raise Exception session['collections'] = [{'title': i.title, 'href': i.href} for i in sword2cnx.get_workspaces(conn)] except: del session['username'] del session['password'] request['errors'] = ["Invalid username or password. Please try again.",] response = { 'form': FormRenderer(form), 'field_list': field_list, 'config': config, } return render_to_response(templatePath, response, request=request) # Get needed info from the service document doc = etree.fromstring(conn.sd.raw_response) # Prep the namespaces. xpath does not like a None namespace. namespaces = doc.nsmap del namespaces[None] # We need some details from the service document. # TODO: This is fragile, since it assumes a certain structure. session['workspace_title'] = doc.xpath('//atom:title', namespaces=namespaces )[0].text session['sword_version'] = doc.xpath('//sword:version', namespaces=namespaces )[0].text session['maxuploadsize'] = doc.xpath('//sword:maxuploadsize', namespaces=namespaces )[0].text # Go to the upload page return HTTPFound(location=request.route_url('choose'))
def enhance(request): check_login(request) session = request.session google_resource_id = "" slideshare_id = "" embed_google = False embed_slideshare = False not_converted = True show_iframe = False form = Form(request, schema=QuestionAnswerSchema) validate_form = form.validate() print form.all_errors() if session.has_key('google-resource-id'): google_resource_id = session['google-resource-id'] if session.has_key('slideshare_id'): slideshare_id = session['slideshare_id'] if fetch_slideshow_status(slideshare_id) == "2": not_converted = False show_iframe = True if google_resource_id!="": embed_google = True if slideshare_id!="": embed_slideshare = True templatePath = "templates/google_ss_preview.pt" if validate_form: introductory_paragraphs = request.POST.get('introductory_paragraphs') question_count=0 cnxml=session["cnxml"]+"""<content><section id="intro-section-title"><title id="introtitle">Introduction</title><para id="introduction-1">"""+introductory_paragraphs+"""</para></section><section id="slides-embed"><title id="slide-embed-title">View the slides</title><figure id="ss-embed-figure"><media id="slideshare-embed" alt="slideshare-embed"><iframe src="http://www.slideshare.net/slideshow/embed_code/"""+slideshare_id+"""" width="425" height="355" /></media></figure></section>""" for i in range(1,6): form_question = request.POST.get('question-'+str(i)) if form_question: form_radio_answer = request.POST.get('radio-'+str(i)) #this give us something like 'answer-1-1'. so our solution is this question_count +=1 if question_count==1: cnxml+="""<section id="test-section"><title>Test your knowledge</title>""" itemlist = "" for j in range(1,10): try: form_all_answers = request.POST.get('answer-'+str(i)+'-'+str(j)) if form_all_answers: itemlist +="<item>" + form_all_answers+"</item>" except: print "No element found" if form_radio_answer: solution = request.POST.get(form_radio_answer) cnxml+="""<exercise id="exercise-"""+str(i)+""""><problem id="problem-"""+str(i)+""""><para id="para-"""+str(i)+"""">"""+str(form_question)+"""<list id="option-list-"""+str(i)+"""" list-type="enumerated" number-style="lower-alpha">"""+str(itemlist)+"""</list></para></problem>""" else: print "ELESE CONDUITION OF radio" solution = request.POST.get('answer-'+str(i)+'-1') cnxml+="""<exercise id="exercise-"""+str(i)+""""><problem id="problem-"""+str(i)+""""><para id="para-"""+str(i)+"""">"""+str(form_question)+"""</para></problem>""" print "FORM RADIO ANSWER",form_radio_answer print "SOLUTION", solution cnxml+=""" <solution id="solution-"""+str(i)+""""> <para id="solution-para-"""+str(i)+"""">"""+solution+"""</para></solution></exercise>""" """form_solution = request.POST.get('solution-'+str(i)) all_post_data = {"data":{"options":form_options,"solution":form_solution,"question":form_question}} for question in all_post_data: options = all_post_data[question]['options'] solution = all_post_data[question]['solution'] asked_question = all_post_data[question]['question'] optionlist="" for option in options: optionlist+="<item>"+option+"</item>""" #cnxml+="""<exercise id="exercise-"""+str(j)+""""><problem id="problem-"""+str(j)+""""><para id="para-"""+str(j)+"""">"""+str(asked_question)+"""<list id="option-list-"""+str(j)+"""" list-type="enumerated" number-style="lower-alpha">"""+str(optionlist)+"""</list></para></problem>""" #cnxml+=""" <solution id="solution-"""+str(j)+""""> <para id="solution-para-"""+str(j)+"""">"""+solution+"""</para></solution></exercise>""" #j+=1 metadata = session['metadata'] if question_count>=1: cnxml += "</section></content></document>" else: cnxml += "</content></document>" workspaces = [(i['href'], i['title']) for i in session['login'].collections] metadata_entry = sword2cnx.MetaData(metadata) zipped_filepath = session['userfilepath'] zip_archive = zipfile.ZipFile(zipped_filepath, 'w') zip_archive.writestr("index.cnxml",cnxml) zip_archive.close() conn = sword2cnx.Connection("http://cnx.org/sword/servicedocument", user_name=session['login'].username, user_pass=session['login'].password, always_authenticate=True, download_service_document=True) collections = [{'title': i.title, 'href': i.href} for i in sword2cnx.get_workspaces(conn)] session['login'].collections = collections workspaces = [(i['href'], i['title']) for i in session['login'].collections] session['workspaces'] = workspaces with open(zipped_filepath, 'rb') as zip_file: deposit_receipt = conn.create( col_iri = workspaces[0][0], metadata_entry = metadata_entry, payload = zip_file, filename = 'upload.zip', mimetype = 'application/zip', packaging = 'http://purl.org/net/sword/package/SimpleZip', in_progress = True) session['dr'] = deposit_receipt session['deposit_receipt'] = deposit_receipt.to_xml() soup = BeautifulSoup(deposit_receipt.to_xml()) data = soup.find("link",rel="edit") edit_iri = data['href'] session['edit_iri'] = edit_iri creator = soup.find('dcterms:creator') username = session['login'].username email = creator["oerdc:email"] url = "http://connexions-oerpub.appspot.com/" post_values = {"username":username,"email":email,"slideshow_id":slideshare_id} data = urllib.urlencode(post_values) google_req = urllib2.Request(url, data) google_response = urllib2.urlopen(google_req) now_string = datetime.datetime.now().strftime('%Y%m%d-%H%M%S') temp_dir_name = '%s-%s' % (request.session['login'].username, now_string) save_dir = os.path.join(request.registry.settings['transform_dir'],temp_dir_name) os.mkdir(save_dir) request.session['upload_dir'] = temp_dir_name cnxml = clean_cnxml(cnxml) save_cnxml(save_dir,cnxml,[]) return HTTPFound(location=request.route_url('metadata')) #return HTTPFound(location=request.route_url('updatecnx')) response = {'form':FormRenderer(form), "slideshare_id":slideshare_id, "google_resource_id":google_resource_id, "embed_google":embed_google, "embed_slideshare":embed_slideshare, "not_converted": not_converted, "show_iframe":show_iframe} return render_to_response(templatePath, response, request=request)