def sections_by_subject(args, store): courses = store.get_courses( term=args.term, subject=args.subject, ) pad = 2 wrapper = TextWrapper( initial_indent=' ' * pad, subsequent_indent=' ' * (4 + pad), ) for course in courses: course = Course(args.subject, course['number']) sections = store.get_sections( course=course, term=args.term, ) if len(sections) != 0: print(course.get_number() + '\n'.join( wrapper.wrap(' '.join([ section['name'] for section in sections ])) )) print('')
def select_platform_course_name(platform_name, course_name): if platform_name == None or course_name == None: return None if course_name == "": return None sql = "SELECT * FROM COURSE WHERE platform_name = %s and (course_name like %s or course_name like %s or course_name like %s or course_name= %s);" courses = [] conn = set_conect() cursor = conn.cursor() try: cursor.execute(sql, (platform_name, '%' + course_name + '%', '%' + course_name, course_name + '%', course_name)) conn.commit() result = cursor.fetchall() for row in result: c = Course(course_name=row[1], course_type=row[2], course_url=row[3], platform_name=row[4]) c.id = row[0] courses.append(c) except: print("select_platform_name error") return None finally: cursor.close() conn.close() return courses
def initcourse(): course1 = Course(course_name="PYTHON", course_type="PYTHON", course_url="https//www.4399.com", platform_name="4399") course2 = Course(course_name="C++", course_type="C", course_url="https//www.7k7k.com", platform_name="7k7k") course3 = Course(course_name="JAVA", course_type="C", course_url="https//www.google.com", platform_name="4399") course4 = Course(course_name="C", course_type="C", course_url="http://baiadu.com", platform_name="baidu") initcourses.append(course1) initcourses.append(course2) initcourses.append(course3) initcourses.append(course4) db.drop_course_table() db.init_course_table() mylist = getInfoFromImmocForPython() print(initcourses) #自己随便写的测试用课程对象列表 print(mylist) #爬虫爬取的信息组成的课程对象列表 db.insert_courses_table(mylist) # db.insert_courses_table(initcourses) return db.select_all_course()
def delc(): if request.method == "POST": course = Course(request.form['cid'], '') course.delete_course() return render_template('home.html') else: return render_template('delcourse.html')
def updatec(): if request.method == 'POST': course = Course(request.form['cid'], request.form['cname']) course.update_course() return render_template('home.html') else: return render_template('updatecourse.html')
def test_deleteid3(self): a = Course(course_name="这是一个测试", course_type="ss", course_url="4399", platform_name="") b = Course(course_name="这是一个测试", course_type="sss", course_url="4399d", platform_name="rt") s = [a, b] db.drop_course_table() db.init_course_table() db.insert_courses_table(s) # print(db.select_all_course()[0].id) self.assertFalse(db.delete_course_table2(None)) a = Course(course_name="这是一个测试", course_type="ss", course_url="4399", platform_name="") b = Course(course_name="这是一个测试", course_type="sss", course_url="4399d", platform_name="rt") s = [a, b] db.drop_course_table() db.init_course_table() db.insert_courses_table(s) # print(db.select_all_course()[0].id) self.assertFalse(db.delete_course_table2(None))
def add_course(): """Add a running course to the database""" print "/new-course called" user_id = session["user_id"] print user_id course = request.form.get("course") polyline = request.form.get("overview-polyline") # print "polyline is ", polyline directions_text = request.form.get("directions-text") directions_distance = request.form.get("directions-distance") start_address = request.form.get("start-address") end_address = request.form.get("end-address") new_course = Course(user_id=user_id, course_name=course, add_date=datetime.now(), start_lat=request.form.get("start-lat"), start_long=request.form.get("start-long"), end_lat=request.form.get("end-lat"), end_long=request.form.get("end-long"), course_distance=request.form.get("distance"), favorite=request.form.get("favorite"), polyline=polyline, directions_text=directions_text, directions_distance=directions_distance, start_address=start_address, end_address=end_address ) new_course.add() return "Course %s has been saved to your courses" % course
def add_course(fields): if 'role' not in session or not session['role'] == 'admin': raise APIError('Insufficient permission', status_code=403) course = Course() for key, value in fields.items(): course.__setattr__(key, value) db.session.add(course) db.session.commit() return course.dict
def test_insertmany6(self): a = Course(course_name="这是一个测试", course_type="ss", course_url="4399d", platform_name="") b = Course(course_name="这是一个测试", course_type="sss", course_url="4399d", platform_name="rt") s = [a, b] self.assertFalse(db.insert_courses_table(s))
def test_delete4(self): a = Course(course_name="这是一个测试", course_type="ss", course_url="4399", platform_name="") b = Course(course_name="这是一个测试", course_type="sss", course_url="4399d", platform_name="rt") s = [a, b] db.insert_courses_table(s) self.assertFalse(db.delete_course_table(None))
def test_selectplatformname4(self): a = Course(course_name="这是一个测试", course_type="ss", course_url="4399", platform_name="") b = Course(course_name="这是一个测试", course_type="sss", course_url="4399d", platform_name="rt") s = [a, b] db.insert_courses_table(s) self.assertEqual(db.select_platform_name(None), None)
def test_selectall1(self): a = Course(course_name="这是一个测试", course_type="sss", course_url="4399", platform_name="s") b = Course(course_name="这是一个测试", course_type="sss", course_url="4399d", platform_name="rt") s = [a, b] db.insert_courses_table(s) self.assertEqual(db.select_all_course()[0].course_name, a.course_name)
def regioncourses(): region_name, _, _ = get_region(request.headers.get("X-SecondLife-Region")) user_key = request.headers.get("X-SecondLife-Owner-Key") user = get_user(user_key) region = Region.get_by_key_name(region_name) if not region is None: query = BlacklistUser.all(keys_only=True) query.ancestor(user) bl_users = [n for n in query] query = BlacklistCourse.all(keys_only=True) query.ancestor(user) bl_courses = [n for n in query] all_courses = [] query = Course.all() query.ancestor(region.key()) query.filter("saved =", True) query.filter("deactivated =", False) query.filter("public =", False) query.filter("user ="******"name") for course in query: all_courses.append( "%s (%s by %s, private);%s" % (course.name, course.type.lower(), course.user.name, str(course.key())) ) courses = deserialize_entities(memcache.get("regioncourses-%s" % region_name)) if courses is None: query = Course.all() query.ancestor(region.key()) query.filter("saved =", True) query.filter("deactivated =", False) query.filter("public =", True) query.order("name") courses = [course for course in query] memcache.set(key="regioncourses-%s" % region_name, value=serialize_entities(courses), time=CACHE_TIME * 6) for course in courses: if course.user.key() not in bl_users and course.key() not in bl_courses: all_courses.append( "%s (%s by %s);%s" % (course.name, course.type.lower(), course.user.name, str(course.key())) ) if all_courses: return Response(";".join(all_courses)) msg = "\nThere are no courses for region %s." % region_name regions = Region.all().filter("course_count >", 0).order("-course_count").fetch(10) msg += "\nTry one of these regions instead:\n" + "\n".join(["http://" + quote(sl_url % r.name) for r in regions]) return Response(msg, status=406)
def generateCourse(name): course = Course() course.coursetitle = name course.description = ("Welcome to the course of " + name) course.credits = random.randint(1, 5) course.studyID = random.choice(studies).studyID course.teacherID = random.choice(teachers).teacherID course.insert() return course
def test_selectplatformname2(self): a = Course(course_name="这是一个测试", course_type="sss", course_url="4399", platform_name="safsd") b = Course(course_name="这是一个测试", course_type="sss", course_url="4399d", platform_name="rt") s = [a, b] db.insert_courses_table(s) self.assertEqual( db.select_platform_name("fs")[0].course_type, a.course_type)
def sections_by_subject(args, store): courses = store.get_courses(term=args.term, subject=args.subject) pad = 2 wrapper = TextWrapper(initial_indent=" " * pad, subsequent_indent=" " * (4 + pad)) for course in courses: course = Course(args.subject, course["number"]) sections = store.get_sections(course=course, term=args.term) if len(sections) != 0: print (course.get_number() + "\n".join(wrapper.wrap(" ".join([section["name"] for section in sections])))) print ""
def input_courses(csvfilename): """ create courses from a .csv file defining them """ with row in csv.DictReader(open(csvfilename)): name = row['name'] name_as_title = row['name_as_title'] path = row['path'] start = default_date Course.create_course( name = name, name_as_title = name_as_title, path = path, start = default_date, copy_generic = True )
def add_course_and_run(): """Add a run to the database.""" print "/new-run in server.py called" start_lat = request.form.get("start-lat") start_long = request.form.get("start-long") end_lat = request.form.get("end-lat") end_long = request.form.get("end-long") add_date = datetime.now() course = request.form.get("course") distance = request.form.get("distance") favorite = request.form.get("favorite") date = request.form.get("date") user_id = session["user_id"] polyline = request.form.get("overview-polyline") directions_text = request.form.get("directions-text") directions_distance = request.form.get("directions-distance") start_address = request.form.get("start-address") end_address = request.form.get("end-address") # print "start_lat is %s, start_long is %s, end_lat is %s, end_long is %s, name is %s, distance is %s, favorite is %s" % (start_lat, start_long, end_lat, end_long, course, distance, favorite) new_course = Course(user_id=user_id, course_name=course, add_date=add_date, start_lat=start_lat, start_long=start_long, end_lat=end_lat, end_long=end_long, course_distance=distance, favorite=favorite, polyline=polyline, directions_text=directions_text, directions_distance=directions_distance, start_address=start_address, end_address=end_address ) new_course.add() # print "course committed" course_id = Course.get_by_course_name(course).course_id d = datetime.strptime(date, "%m/%d/%Y") duration = request.form.get("duration") duration = int(duration) new_run = Run(user_id=user_id, course_id=course_id, run_date=d, duration=duration) new_run.add() return "Your run was saved"
def submit_newcourse(): """ create new course """ #print_debug('submit_newcourse: {}'.format(request.form)) name = request.form['name'] # e.g. "Intro Programming" path = request.form[ 'path'] # should have form term/folder e.g. fall2018/cs1 copyfrom = request.form['copyfrom'] # e.g. "fall2017/cs1" startdate = path_to_startdate(path) title = name_to_htmltitle(name) print_debug(' submit_newcourse: name = "{}"'.format(name)) print_debug(' path = "{}"'.format(path)) print_debug(' copyfrom = "{}"'.format(copyfrom)) newcourse = Course.create_course(name, path, start=startdate, name_as_title=title, copyfrom=copyfrom) for name in request.form['faculty'].split(','): try: faculty = Person.get(username=name.strip()) except: faculty = None if not faculty: try: faculty = Person.get(username=name.strip()) except: faculty = None if faculty: today = str(Time())[:10] newcourse.enroll(faculty, 'faculty', today, create_work=False) return newcourse.url
def add_course(): code = request.json.get('code') name = request.json.get('name') location = request.json.get('location') time = request.json.get('time') resp = {} msg = 'Add course successful' if (g.user.role != 0): # abort(400) msg = 'User has no authority' elif (not code or not name or not location or not time): msg = 'Course message lost' else: course = Course(code=code, name=name, location=location, time=time, teacher_id=g.user.id) if (Course.query.filter_by(code=code).first() is not None): msg = 'The course already exists' # abort(400) else: db.session.add(course) db.session.commit() resp['msg'] = msg return get_response(resp)
def test_insert9(self): a = Course(course_name="hh", course_type="ss", course_url="4399", platform_name="sss") db.insert_course_table(a) self.assertFalse(db.insert_course_table(a))
def test_insert6(self): a = Course(course_name="这是一个测试这是一个测试一个测试", course_type="ss", course_url="4399", platform_name="sss") self.assertTrue(db.insert_course_table(a))
def test_selectplatformname3(self): a = Course(course_name="这是一个测试", course_type="ss", course_url="4399", platform_name="f") b = Course(course_name="这是一个测试", course_type="sss", course_url="4399d", platform_name="rt") c = Course(course_name="这是s测试", course_type="325s", course_url="439d", platform_name="y") s = [a, b] db.insert_courses_table(s) self.assertEqual(db.select_platform_name(c.platform_name), [])
async def getAllCousWS(): # 载入 Course # courses = [] # 初始化 SQL rs = await handler.getAllCouse() # 将结果 模型化并返回 res = [] if rs is not None: for i in rs: res.append(Course(**i)) # 将 course list 转变为 Cws list cous = [] for item in res: cous.append(CourseWithStudents(course=item, students=[])) # 载入 Students for item in cous: # 初始化 SQL rs = await handler.getStuGrade(item.course.cno) # 将结果 模型化并返回 if rs is not None: for i in rs: item.students.append(Student(**i)) # 返回 Cws return cous
def get_course_list(self) -> Iterator[Course]: """Gets the list of available courses. :raises PodcastProviderError: If an error occurs getting the course list. :return: A list of URLs for each course podcast home. """ # Get list of courses from video page get_video_service_base = self.session.get(self.video_service_base_url + "/lectures") # Check status code valid if get_video_service_base.status_code != 200: raise PodcastProviderError( f"Could not get video service - Service responded with status code " f"{get_video_service_base.status_code}") # Status code valid, extract courses get_video_service_base_soup = BeautifulSoup( get_video_service_base.content, features="html.parser") course_items_html = get_video_service_base_soup.find("nav", {"id": "sidebar-nav"}).ul.contents[3]\ .find_all("li", {"class": "series"}) return map( lambda x: Course(x.a.string, x.a["href"], x.a.string[-7:].replace( "/", "-")), course_items_html)
def test_insert2(self): a = Course(course_name="", course_type="", course_url="", platform_name="") self.assertTrue(db.insert_course_table(a))
def run_detail_json(): """Return JSON of individual run.""" run_data = {} run_id = request.form.get("runId") run = Run.query.get(run_id) course = Course.get_by_id(run.course_id) print course string_run_date = datetime.strftime(run.run_date, "%m/%d/%Y") waypoints = util.decode_polyline(course.polyline) run_data = {"run_id": run.run_id, "course_name": course.course_name, "run_date": string_run_date, "course_distance": course.course_distance, "duration": run.duration, "waypoints": waypoints, "directions_text": course.directions_text, "directions_distance": course.directions_distance, "start_address": course.start_address, "end_address": course.end_address } print run_data return jsonify(run_data)
def test_delete5(self): a = Course(course_name="这是一个测试", course_type="ss", course_url="4399", platform_name="") db.delete_all_course_table() self.assertTrue(db.delete_course_table(a))
def test_delete3(self): a = Course(course_name="这是一个测试", course_type="ss", course_url="4399", platform_name="") b = Course(course_name="这是一个测试", course_type="sss", course_url="4399d", platform_name="rt") s = [a, b] db.insert_courses_table(s) c = Course(course_name="测试", course_type="ssds", course_url="sjw", platform_name="t") self.assertTrue(db.delete_course_table(c))
def test_selectplatformcoursename2(self): a = Course(course_name="物理", course_type="sss", course_url="4399", platform_name="s") b = Course(course_name="化学", course_type="sss", course_url="4399d", platform_name="rt") c = Course(course_name="高数", course_type="sss", course_url="4399s", platform_name="rt") s = [a, b, c] db.insert_courses_table(s) self.assertEqual(db.select_platform_course_name("rt", " "), [])
def create(): if request.method == 'POST': content = request.get_json(silent=True) fullName = cgi.escape(content['username']) className = cgi.escape(content['classname']) hashids = Hashids(salt=settings.HASHID_SALT,min_length=6) increment() count = get_count() hashid = hashids.encode(count) courseId = DEFAULT_COURSE_PREFIX + hashid userId = request.cookies.get('remote_userid') if 'remote_userid' in request.cookies else generate_user_id() userColor = request.cookies.get('remote_usercolor') if 'remote_usercolor' in request.cookies else generate_color() host = app.config.get('host') resp = make_response(hashid) # Add course to database key = courseId course = Course.get_or_insert(key, courseId=courseId, teacherName=fullName) course.put() # Add teacher to course # Create OpenTok session opentok_sdk = OpenTok(OPENTOK_API_KEY, OPENTOK_API_SECRET) # use tokbox server to route media streams; # if you want to use p2p - change media_mode to MediaModes.relayed opentok_session = opentok_sdk.create_session(media_mode = MediaModes.routed) opentok_token = opentok_sdk.generate_token(opentok_session.session_id) key = courseId + userId user = Student.get_or_insert(key, courseId = courseId, studentId = userId, fullName = fullName, color = userColor, role = 'TEACHER', opentokSessionId = opentok_session.session_id, opentokToken = opentok_token ) user.put() # Set user cookies (teacher role) auth = json.loads(request.cookies.get('remote_auth')) if 'remote_auth' in request.cookies else {} auth[hashid] = { 'role': 'Instructor', 'opentok_api_key': OPENTOK_API_KEY, 'opentok_session_id': user.opentokSessionId, 'opentok_token': user.opentokToken } resp.set_cookie('remote_userfullname', fullName) resp.set_cookie('remote_auth', json.dumps(auth)) resp.set_cookie('remote_userid', userId) resp.set_cookie('remote_usercolor', userColor) #resp.set_cookie('remote_userinitials', userInitials) return resp return redirect('/main#/create')
def setstate(): try: user_key = request.headers.get("X-SecondLife-Owner-Key") user = get_user(user_key) state = request.args.get("state") course_id = request.args.get("courseid") course = Course.get(Key(course_id)) s = State(parent=user, course=course, state=state, started=datetime.now()) s.put() memcache.set(key="state-%s" % user_key, value=serialize_entities(s), time=CACHE_TIME) return Response() except db.Timeout: msg = "\nState was not saved. The database timed out." logging.error(msg) return Response(msg, status=500) except CapabilityDisabledError: msg = "\nState was not saved. Database could not be written to." logging.error(msg) return Response(msg, status=500) except TransactionFailedError: msg = "\nState was not saved. Transaction failed." logging.error(msg) return Response(msg, status=500) except Exception, e: if DEBUG: print_exc() logging.error(str(e)) return Response("\nState was not saved. %s." % e, status=500)
def txn(): region = Region.get_by_key_name(region_name) if region is None: region = Region(key_name=region_name, name=region_name, cx=cx, cy=cy) region.put() course = Course( name=course_name, parent=region.key(), start_region=region, user=user.key(), public=access == "PUBLIC", type=type, ) course.put() memcache.set(key="course-%s" % user_key, value=serialize_entities(course), time=CACHE_TIME)
def search_course_detail_by_name(): """Show info about course.""" print "search term is ", request.args.get("search") course = Course.get_by_course_name(request.args.get("search")) print course return redirect("courses/%s" % course.course_id)
def parse(self, response): course_info = response.css( 'script[class="js-schema"]::text').extract_first() course_info = json.loads(course_info) Course.create( course_id=uuid.uuid4(), course_title=course_info['@graph'][1]['name'], course_description=course_info['@graph'][1]['description'], language='English', level='All level', student_enrolled=0, ratings=0, overall_rating=0, course_url=response.url, cover_image=course_info['@graph'][1]['image']['url'], source='edx')
def save(self): # get the course values from the ui title = self.view.get_title() subject = self.view.get_subject() # store the new values in the course variable course = Course(-1, self.semester, title, subject) # save the changes into the db BGModelController.add_course(course)
def post(self): resources = Resource.all() course = Course.get_by_id(int(self.request.get('course'))) selected_resources = [] for r in resources: if r.res_course.key().id() == course.key().id(): selected_resources.append(r) template_values = {'course' : course, 'resources' : selected_resources } path = os.path.join(os.path.dirname(__file__), 'html/results.html') self.response.out.write(template.render(path, template_values))
def all_course_data(): """Return JSON of all courses.""" all_course_data = {} courses = Course.get_all() for course in courses: string_add_date = datetime.strftime(course.add_date, "%m/%d/%Y") all_course_data[course.course_id] = {"course_id": course.course_id, "course_name": course.course_name, "add_date": string_add_date, "course_distance": course.course_distance} return jsonify(all_course_data)
def savecourse(): try: user_key = request.headers.get("X-SecondLife-Owner-Key") user = get_user(user_key) region_name, cx, cy = get_region(request.headers.get("X-SecondLife-Region")) region = Region.get_or_insert(region_name, name=region_name, cx=cx, cy=cy) course = deserialize_entities(memcache.get("course-" + user_key)) if course is None: query = Course.all() query.filter("user ="******"saved =", False) query.filter("deactivated =", False) course = query.get() if not course: return Response("Course was not saved, something went wrong.", status=406) course.end_region = region marks = [] for key in course.marks: mark = Mark.get(key) mark.saved = True marks.append(mark) db.put(marks) course.length = course_length(course) course.saved = True course.put() memcache.delete("course-" + user.key().name()) return Response("\nCourse %s saved." % course.name) except db.Timeout: msg = "New course failed. The database timed out." logging.error(msg, status=500) return Response(msg) except CapabilityDisabledError: msg = "New course failed. Database could not be written to." logging.error(msg) return Response(msg, status=500) except TransactionFailedError: msg = "New course failed. Transaction failed." logging.error(msg) return Response(msg, status=500) except Exception, e: logging.error(str(e)) if DEBUG: print_exc() return Response("New course failed.", status=500)
def course(): course_key = request.args.get("courseid") region_name, _, _ = get_region(request.headers.get("X-SecondLife-Region")) region = Region.get_by_key_name(region_name) if not region is None and course_key: course = deserialize_entities(memcache.get("course-%s" % course_key)) if course is None: course = Course.get(course_key) memcache.set(key="course-%s" % course_key, value=serialize_entities(course), time=CACHE_TIME) if not course is None: if course.comment: return Response("\nAbout this course:\n" + course.comment) else: return Response() else: return Response("\nCourse not found.", status=404) else: return Response("\nCourse not found.", status=404)
def post(self): upload_files = self.get_uploads('file') studentid = self.request.get('studentid') password = self.request.get('password') users = User.all() user = None for u in users: if u.studentid == studentid: if u.password == password: user = u break else: break if user: title = self.request.get('title') course = Course.get_by_id(int(self.request.get('course'))) blob_info = upload_files[0] if blob_info: bly = bitly.BitLy('o_2tov7hc8mi', 'R_e863d338484e0fbb60cf1416ce3ae6de') uri = str(os.environ.get('SERVER_NAME')) uri = uri + '/resource/' + str(blob_info.key()) short = bly.shorten(uri) uri2 = 'http://%s' % uri short = short['results'][uri2]['shortUrl'] if short: pass else: short = 'uri2' resource = Resource(res_title=title, res_filekey=str(blob_info.key()), res_course=course, res_filekey2=str(blob_info.key()), res_short_uri=short, res_author = user) resource.put() self.redirect('/resource/%s' % str(blob_info.key())) else: self.redirect('/upload/wrong_file') else: self.redirect('/upload/wrong_user')
def mycourses(): user_key = request.headers.get("X-SecondLife-Owner-Key") user = get_user(user_key) region_name, _, _ = get_region(request.headers.get("X-SecondLife-Region")) region = Region.get_by_key_name(region_name) courses = [] if not region is None: query = Course.all() query.ancestor(region) query.filter("user ="******"saved =", True) query.filter("deactivated =", False) for course in query: courses.append("%s (%s by %s);%s" % (course.name, course.type.lower(), course.user.name, str(course.key()))) logging.info(courses) if courses: return Response(";".join(courses)) else: return Response("\nYou have no courses in region %s." % region_name, status=406)
def blacklistcourse(): try: user_key = request.headers.get("X-SecondLife-Owner-Key") user = get_user(user_key) course_id = request.args.get("courseid") region_name, _, _ = get_region(request.headers.get("X-SecondLife-Region")) region = Region.get_by_key_name(region_name) course = Course.get(Key(course_id)) query = BlacklistCourse.all() query.ancestor(user) query.filter("course =", course.key()) bl_course = query.get() if bl_course is None: blc = BlacklistCourse(parent=user, course=course, region=region) blc.put() return Response("\nCourse `%s` was added to your blacklist." % course.name) else: bl_course.delete() return Response("\nCourse `%s` was removed from your blacklist." % course.name) except db.Timeout: msg = "\nCourse was not blacklisted. The database timed out." logging.error(msg) return Response(msg, status=500) except CapabilityDisabledError: msg = "\nCourse was not blacklisted. Database could not be written to." logging.error(msg) return Response(msg, status=500) except TransactionFailedError: msg = "\nCourse was not blacklisted. Transaction failed." logging.error(msg) return Response(msg, status=500) except Exception, e: if DEBUG: print_exc() logging.error(str(e)) return Response("\nCourse was not blacklisted. %s." % e, status=500)
def course_detail_json(): """Return JSON of individual course.""" course_data = {} course_id = request.form.get("courseId") course = Course.get_by_id(course_id) string_add_date = datetime.strftime(course.add_date, "%m/%d/%Y") waypoints = util.decode_polyline(course.polyline) course_data = {"course_id": course.course_id, "course_name": course.course_name, "add_date": string_add_date, "course_distance": course.course_distance, "waypoints": waypoints, "directions_text": course.directions_text, "directions_distance": course.directions_distance, "start_address": course.start_address, "end_address": course.end_address } print course_data return jsonify(course_data)
def get(self): departments = Department.all() comp = None for dep in departments: course = Course(cour_name = 'course1 of '+ dep.dep_name, cour_department=dep) course.put() if dep.dep_name == 'Department of Computer Science and Information Engineering': comp = dep i2c = Course(cour_name = 'Introduction to Computers', cour_department=comp) i2c.put() template_values = {'title': 'data loaded', 'message': 'courses loaded', 'method': 'get', 'action': '/', 'value': 'continue' } path = os.path.join(os.path.dirname(__file__), 'html/message.html') self.response.out.write(template.render(path, template_values))
def course_type(value): course = Course.parse(value) if course is None: raise argparse.ArgumentTypeError("invalid format") return course
def edit(): try: user_key = request.headers.get("X-SecondLife-Owner-Key") user = get_user(user_key) region_name, cx, cy = get_region(request.headers.get("X-SecondLife-Region")) region = Region.get_or_insert(region_name, cx=cx, cy=cy) course_key = request.args.get("coursekey") action = request.args.get("action") course_name = request.args.get("coursename") mark_name = request.args.get("markname") mark = request.args.get("mark") turn = request.args.get("turn") comment = request.args.get("comment") if action in ("REPLM", "ADDM") and mark: x, y, _ = vector2floats(mark) gx = cx + x gy = cy + y course = Course.get(Key(course_key)) if course is None or course.user.key() != user.key(): return Response("\nSomething went wrong, course was not modified.") now = datetime.now() state = get_state(user) if state is None: raise ValueError("State missing!") memcache.delete("regioncourses-%s" % region_name) memcache.delete("course-%s" % course_key) i = state.mark if action == "DELC": deleted = deactivate_course(course) return Response("Course %s deleted. %d unused marks deleted." % (course.name, deleted)) elif action == "RENC" and course_name: old_name = course.name course.name = course_name.strip() course.last_modified = now course.put() return Response("\nCourse %s was renamed to %s." % (old_name, course.name)) elif action == "TPP": course.public = not course.public course.last_modified = now course.put() return Response("Course %s is now %s." % (course.name, "public" if course.public else "private")) elif action == "REPLM": msg = check_new_mark(region, course, turn, i, gx, gy) if msg: return Response(msg, status=406) mark = Mark.get(course.marks[i]) mark.x = x mark.y = y mark.gx = gx mark.gy = gy mark.put() course.turns[i] = turn course.length = course_length(course) course.last_modified = now course.put() return Response("\nMark %d was replaced by a new mark." % (i + 1)) elif action == "DELM": if len(course.marks) == MIN_COURSE_LENGTH: return Response( "\nYou cannot delete a mark from a %d mark course, you can only replace them." % MIN_COURSE_LENGTH ) elif 1 <= i < len(course.marks): mark = Mark.get(course.marks[i]) del course.marks[i] del course.turns[i] dec_mark(mark) course.length = course_length(course) course.last_modified = now course.put() return Response("\nMark %d of course %s was deleted." % (i + 1, course.name)) else: return Response("\nYou cannot delete the start/end mark, you can only replace them.") elif action == "ADDM": msg = check_new_mark(region, course, turn, i, gx, gy) if msg: return Response(msg, status=406) if 0 <= i < len(course.marks): mark = Mark(region=region, x=x, y=y, gx=gx, gy=gy, parent=user.key()) mark.put() course.marks.insert(i + 1, mark.key()) course.turns.insert(i + 1, turn) course.length = course_length(course) course.last_modified = now course.put() return Response("\nA %s mark was placed after mark %d of course %s." % (turn, i + 1, course.name)) else: return Response("\nYou cannot add a mark after the finish mark.") elif action == "ANNC": course.comment = comment[:499] course.last_modified = now course.put() if len(comment) < 500: return Response("\nA comment was added to course %s." % course.name) else: return Response("\nThe comment was truncated to 500 characters and added to course %s." % course.name) elif action == "GMN" and mark_name: mark = Mark.get(course.marks[i]) old_name = mark.name mark.name = mark_name.strip() mark.put() if old_name: return Response("\Mark %s was renamed to %s." % (old_name, mark.name)) else: return Response("\nMark %d was named %s" % (i, mark.name)) elif action == "ANNM": mark = Mark.get(course.marks[i]) mark.comment = comment[:499] mark.put() if len(comment) < 500: return Response("\nA comment was added to mark %d of course %s." % (i + 1, course.name)) else: return Response( "\nThe comment was truncated to 500 characters and added to mark %d of course %s." % (i + 1, course.name) ) except db.Timeout: msg = "\nCourse was not modified. The database timed out." logging.error(msg) return Response(msg, status=500) except CapabilityDisabledError: msg = "\nCourse was not modified. Database could not be written to." logging.error(msg) return Response(msg, status=500) except TransactionFailedError: msg = "\nCourse was not modified. Transaction failed." logging.error(msg) return Response(msg, status=500) except Exception, e: if DEBUG: print_exc() logging.error(e) return Response("\nCourse was not modified. %s." % e, status=500)
def addmark(): try: user_key = request.headers.get("X-SecondLife-Owner-Key") user = get_user(user_key) region_name, cx, cy = get_region(request.headers.get("X-SecondLife-Region")) x, y = get_position(request.headers.get("X-SecondLife-Local-Position")) turn = request.args.get("turn") n = int(request.args.get("n", 0)) course = deserialize_entities(memcache.get("course-%s" % user_key)) if course is None: query = Course.all() query.filter("user ="******"saved =", False) query.filter("deactivated =", False) course = query.get() if not course: return Response("Course was not saved, something went wrong.", status=406) gx = cx + x gy = cy + y region = Region.get_or_insert(region_name, name=region_name, cx=cx, cy=cy) msg = check_new_mark(region, course, turn, n, gx, gy) if msg: return Response(msg, status=406) marks = deserialize_entities(memcache.get("marks-%s" % user_key)) if marks is None: query = Mark.all() query.ancestor(user.key()) query.filter("region =", region) query.filter("deactivated =", False) marks = [m for m in query] memcache.set(key="marks-%s" % user_key, value=serialize_entities(marks), time=CACHE_TIME) close_marks = sorted( [(m, dist(gx, gy, m.gx, m.gy)) for m in marks if close(gx, gy, m.gx, m.gy)], key=lambda o: o[1] ) if close_marks: mark = close_marks[0][0] mark.used += 1 mark.put() else: mark = Mark(region=region, x=x, y=y, gx=gx, gy=gy, parent=user.key()) mark.put() course.marks.append(mark.key()) course.turns.append(turn) course.put() if not marks is None: marks.append(mark) else: marks = [mark] memcache.set(key="marks-%s" % user_key, value=serialize_entities(marks), time=CACHE_TIME) memcache.set(key="course-%s" % user_key, value=serialize_entities(course), time=CACHE_TIME) if turn == "START": s = "\nStart mark saved. Go to the next mark and click the HUD." elif turn == "FINISH": s = "\nFinish mark saved." else: s = "\nMark %d saved. Go to the next mark and click the HUD." % len(course.marks) if close_marks: d = dist(gx, gy, mark.gx, mark.gy) return Response(s + " This mark was merged with a predefined mark %.1fm. away." % round(d, 1)) else: return Response(s) except db.Timeout: msg = "\nMark was not saved. The database timed out." logging.error(msg) return Response(msg, status=500) except CapabilityDisabledError: msg = "\nMark was not saved. Database could not be written to." logging.error(msg) return Response(msg, status=500) except TransactionFailedError: msg = "\nMark was not saved. Transaction failed." logging.error(msg) return Response(msg, status=500) except Exception, e: if DEBUG: print_exc() logging.error(e) return Response("\nMark was not saved. %s." % e, status=500)
def route_detail(course_id): """Show info about course.""" print Course.get_by_id(course_id) return render_template("course.html", course=Course.get_by_id(course_id))
def export(mine=0, uuid=""): user_key = request.headers.get("X-SecondLife-Owner-Key") user = get_user(user_key) if not user_key is None else None if not user is None: csv = deserialize_entities(memcache.get("csv-user_key-%d-%s" % (mine, user_key))) if not csv is None: # logging.info("csv-user_key-%d-%s" % (mine, user_key)) # logging.info("using cache: user_key") return Response(url_for("export", _external=True, mine=str(mine), uuid=user.uuid)) if uuid: csv = deserialize_entities(memcache.get("csv-uuid-%d-%s" % (mine, uuid))) if not csv is None: # logging.info("csv-uuid-%d-%s" % (mine, uuid)) # logging.info("using cache: uuid") return Response(csv, mimetype="application/excel") else: return Response(status=204) # logging.info("not using cache: %d %s" % (mine, uuid)) query = Course.all() query.filter("saved =", True) query.filter("deactivated =", False) if mine: query.filter("user = "******"public =", True) marks = {} buffer = StringIO() w = writer(buffer, delimiter=";") w.writerow( ( "Region", "Name", "Comment", "Creator", "Creator key", "Created", "Last modified", "Public", "Type", "Mark: Region, Turn, Name, Comment, Local x, Local y, Global x, Gobal y, Created", ) ) for course in query: row = [ course.start_region.name, course.name, course.comment, course.user.name, course.user.key().name(), course.created.strftime("%Y-%m-%d %H:%M:%S"), course.last_modified.strftime("%Y-%m-%d %H:%M:%S"), "Yes" if course.public else "No", course.type.capitalize(), ] for i, mkey in enumerate(course.marks): if mkey in marks: mark = marks[mkey] else: mark = Mark.get(mkey) marks[mark.key()] = mark row.append( ",".join( ( mark.region.name, course.turns[i], mark.name or "", mark.comment or "", str(mark.x), str(mark.y), str(mark.gx), str(mark.gy), mark.created.strftime("%Y-%m-%d %H:%M:%S"), ) ) ) w.writerow(row) value = serialize_entities(buffer.getvalue()) memcache.set_multi( {"user_key-%d-%s" % (mine, user_key): value, "uuid-%d-%s" % (mine, user.uuid): value}, key_prefix="csv-", time=CACHE_TIME * 24, ) # logging.info(url_for("export", _external=True, mine=str(mine), uuid=user.uuid)) return Response(url_for("export", _external=True, mine=str(mine), uuid=user.uuid))
def addcourse(): try: user_key = request.headers.get("X-SecondLife-Owner-Key") user = get_user(user_key) course_name = request.args.get("coursename") access = request.args.get("access") type = request.args.get("type") region_name, cx, cy = get_region(request.headers.get("X-SecondLife-Region")) if not course_name.strip(): return Response("Course was not saved, invalid course name.", status=406) query = Course.all() query.filter("saved =", False) query.filter("deactivated = ", False) query.filter("user ="******"PUBLIC", type=type, ) course.put() memcache.set(key="course-%s" % user_key, value=serialize_entities(course), time=CACHE_TIME) db.run_in_transaction(txn) if dc: return Response( "\nDeleted %d unsaved course(s) and %d mark(s). New course %s ready for region %s." % (dc, dm, course_name, region_name) ) else: return Response("\nNew course %s ready for region %s." % (course_name, region_name)) except db.Timeout: msg = "\nNew course failed. The database timed out." logging.error(msg, status=500) return Response(msg) except CapabilityDisabledError: msg = "\nNew course failed. Database could not be written to." logging.error(msg) return Response(msg, status=500) except TransactionFailedError: msg = "\nNew course failed. Transaction failed." logging.error(msg) return Response(msg, status=500) except Exception, e: logging.error(str(e)) if DEBUG: print_exc() return Response("\nNew course failed.", status=500)