`
oywl2008
  • 浏览: 1050545 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

One Pyton Test Project

 
阅读更多

 

main.py
# coding=utf-8
from wsgiref.simple_server import make_server
from urlparse import parse_qs
import json

import router

SERVER_PORT = 8080
API_TOKEN = 'z8675309q'

# Starts the server
def start_server():

    server = make_server('', SERVER_PORT, app)

    print "serving at port", SERVER_PORT
    server.serve_forever()


# Basic app hook
def app(environ, start_response):

    request_path = environ['PATH_INFO']
    query_params = parse_qs(environ['QUERY_STRING'])

    request_bodysize = int(environ['CONTENT_LENGTH'])
    request_body = environ['wsgi.input'].read(request_bodysize)
    json_body = json.loads(request_body)

    token = json_body.get('token')
    if token is not None and token != API_TOKEN:
        start_response('403 FORBIDDEN', [('Content-type', 'application/json')])
        return json.dumps({"ok": False, "error": "invalid_token"})

    # route the request
    start_response('200 OK', [('Content-type', 'application/json')])
    return json.dumps(router.HandleRouting(request_path, query_params, json_body))

start_server()

 

router.py

# coding=utf-8

import storage

def HandleRouting(path, query_parameters, body):

    # Divert based on path
    if path == '/api/course.create':
        return storage.create_course(body['name'], body['credits'], body['type'])
    if path == '/api/course.addOffering':
        return storage.create_course_offering(body['course_id'], body['instructor_id'], body['year'], body['term'], body['days'], body['time'], body['capacity'])
    if path == '/api/course.getOfferings':
        return storage.get_course_offerings(body['course_id'])
    if path == '/api/course.enroll':
        return storage.create_enrollment(body['course_offering_id'], body['student_id'])
    if path == '/api/student.add':
        return storage.addStudent(body['name'])
    if path == '/api/instructor.add':
        return storage.add_instructor(body['name'])

    # can't find an associated endpoint
    return {
        "ok": False,
        "error": "unknown_method"
    }

 storage.py

# coding=utf-8
import mysql.connector

# Creates a course in the database
def create_course(name, credits, type):

    connection = mysql.connector.connect(user='root', password='super-secret-password', host='localhost', database='registrar')
    cursor = connection.cursor()

    cursor.execute('INSERT INTO COURSES (name, credits, type) VALUES("' + name + '",' + str(credits) + ',"' + type + '")')
    course_id = cursor.lastrowid

    connection.commit()
    connection.close()

    return {
        "ok": True,
        "course_id": course_id,
    }


def addStudent(name):
    """Adds a new student by first name and last name. The combination must be unique."""

    connection = mysql.connector.connect(user='root', password='super-secret-password', host='localhost', database='registrar')
    cursor = connection.cursor()

    cursor.execute('INSERT INTO students (name) VALUES (%(name)s)', {"name": name})
    student_id = cursor.lastrowid

    connection.commit()
    connection.close()

    return {
        "ok": True,
        "student_id": student_id,
    }


# Adds a new instructor to the database
def add_instructor(name):

    connection = mysql.connector.connect(user='root', password='super-secret-password', host='localhost', database='registrar')
    cursor = connection.cursor()

    cursor.execute('INSERT INTO instructors (name) VALUES (%(name)s)', {"name": name})
    student_id = cursor.lastrowid

    connection.commit()
    connection.close()

    return {
        "ok": True,
        "student_id": student_id,
    }


# Adds a new course offering
def create_course_offering(course_id, instructor_id, year, term, days, time, capacity):

    # Validate days is in the allowed set
    allowed_days = ['M', 'W', 'F', 'MW', 'WF', 'MWF', 'T', 'Tr', 'TTr']
    found = False
    for allowed_days_option in allowed_days:
        if allowed_days_option == days:
            found = True
            break

    if not found:
        return {
            "ok": False,
            "error": "invalid_days",
        }

    # Create the course offering
    connection = mysql.connector.connect(user='root', password='super-secret-password', host='localhost', database='registrar')
    cursor = connection.cursor()

    cursor.execute('INSERT INTO course_offerings (course_id, instructor_id, year, term, days, time, capacity) VALUES (%s, %s, %s, %s, %s, %s, %s)', (course_id, instructor_id, year, term, days, time, capacity))
    course_offering_id = cursor.lastrowid

    connection.commit()
    connection.close()

    return {
        "ok": True,
        "course_offering_id": course_offering_id,
    }


def get_course_offerings(course_id):
    """Gets course offering information for the specified course id"""

    connection = mysql.connector.connect(user='root', password='super-secret-password', host='localhost', database='registrar')
    c1 = connection.cursor(buffered=True)
    c1.execute('SELECT id, instructor_id, year, term, days, time, capacity FROM course_offerings WHERE course_id=%(course_id)s', {"course_id": course_id})

    # Enumerate the retrieved course offerings
    offerings = []
    for (id, instructor_id, year, term, days, time, capacity) in c1:

        # Get instructor name
        c2 = connection.cursor()
        c2.execute('SELECT name FROM instructors WHERE id=%(id)s', {"id": instructor_id})
        row = c2.fetchone()

        if row is not None:
            instructor_name = row[0]

        # Determine remaining capacity
        c3 = connection.cursor()
        c3.execute('select count(*) as count from enrollments where course_offering_id=%(id)s', {"id": id})
        row = c3.fetchone()
        count = row[0]
        remaining_capacity = capacity - count

        offerings.append({
            'course_offering_id': id,
            'instructor': instructor_name,
            'year': year,
            'term': term,
            'days': days,
            'time': time,
            'remaining_capacity': remaining_capacity
        })

    connection.close()
    
    # Return results
    return {
        "ok": True,
        "course_offerings": offerings,
    }


def create_enrollment(course_offering_id, student_id):
    """Enrolls a student to a specified course offering"""
    connection = mysql.connector.connect(user='root', password='super-secret-password', host='localhost', database='registrar')

    # First check if there's space in the course offering
    c1 = connection.cursor()
    c1.execute('SELECT capacity FROM course_offerings WHERE id=%(id)s', {"id": course_offering_id})
    capacity = c1.fetchone()[0]

    c2 = connection.cursor()
    c2.execute('SELECT COUNT(*) FROM enrollments WHERE course_offering_id=%(id)s', {"id": course_offering_id})
    count = c2.fetchone()[0]
    
    if count >= capacity:
        return {
            "ok": False,
            "error": "capacity_reached",
        }

    # Enroll the student
    c3 = connection.cursor()
    c3.execute('INSERT INTO enrollments (course_offering_id, student_id) VALUES (%s, %s)', (course_offering_id, student_id))

    connection.commit()
    connection.close()

    return {
        "ok": True,
    }

 

 

 

 

schema.sql

 

DROP DATABASE registrar;
CREATE DATABASE registrar;
USE registrar;

CREATE TABLE `COURSES` (
    `id` int NOT NULL AUTO_INCREMENT,
    `name` varchar(255) NOT NULL,
    `credits` int(11) NOT NULL,
    `type` enum('course','lab','combined') NOT NULL,
    PRIMARY KEY (`id`),
    UNIQUE KEY `name_type_unique` (`name`, `type`),
    KEY `type` (`type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `course_offerings` (
    `id` int NOT NULL AUTO_INCREMENT,
    `course_id` int NOT NULL,
    `instructor_id` int NOT NULL,
    `year` tinyint NOT NULL,
    `term` enum('summer','spring','fall') NOT NULL,
    `days` varchar(100) NOT NULL,
    `time` varchar(100) NOT NULL,
    `capacity` tinyint NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `students` (
    `id` tinyint NOT NULL AUTO_INCREMENT,
    `name` varchar(100) DEFAULT NULL,
    PRIMARY KEY (`id`),
    UNIQUE KEY `id_name_unique` (`id`, `name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `instructors` (
    `id` int NOT NULL AUTO_INCREMENT,
    `name` varchar(100) DEFAULT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `enrollments` (
    `id` int NOT NULL AUTO_INCREMENT,
    `course_offering_id` int(11) NOT NULL,
    `student_id` int(11) NOT NULL,
    `student_name` varchar(100) DEFAULT NULL,
    PRIMARY KEY (`id`),
    UNIQUE KEY `id_student_id_unique` (`id`, `student_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

 

 

Course Enrollment System (Registrar)

Prompt

You are on a 2-person developer team tasked with writing a rudimentary course enrollment system for a small college. Your solution includes a backend written in Python and uses a MySQL database for permanent data storage.

You have been tasked with reviewing your fellow engineer's latest pull request! Please review the submitted changes for correctness and best practices, all the while ensuring that it fulfills the project requirements listed below. If you’re not a Python expert, no worries; we won’t be looking for comments specific to the sample’s programming language.

This is a lengthy pull request with a wide range of mistakes throughout; We do not require you to enumerate all of the mistakes in order to receive a passing grade, but ensure that you've provided feedback on a few different types of problems. We recommend reading the code completely at least once before beginning to provide feedback. Please spend no more than about an hour reviewing the pull request.

For inspiration, read our engineering blog post about code review best practices.

System Requirements

  • Add courses and course offerings
  • Link instructors to course offerings
  • Add students
  • Enroll students in course offerings
    • Course offerings have limited capacity
    • Students also have limited capacity - no single student can enroll in more than five course offerings per semester

API Usage

The following examples demonstrate how to use the enrollment system's API.

curl localhost:8080/api/student.add -d '{"name": "Yoshi", "token": "z8675309q"}'

curl localhost:8080/api/course.create -d '{"name": "COMP200", "credits": 3, "type": "lab", "token": "z8675309q"}'

curl localhost:8080/api/instructor.add -d '{"name": "Dr. Mario", "token": "z8675309q"}'

curl localhost:8080/api/course.addOffering -d '{"course_id": 1, "instructor_id": 2, "year": 2018, "term": "Spring", "days": "MWF", "time": "9:00", "capacity": 10, "token": "z8675309q"}'

curl localhost:8080/api/course.getOfferings -d '{"course_id": "1", "token": "z8675309q"}'

curl localhost:8080/api/course.enroll -d '{"course_offering_id": "1", "student_id": 1, "token": "z8675309q"}'

 

 

 

 

 

 

 

分享到:
评论

相关推荐

    c socket pyton socket

    根据提供的文件信息,我们可以归纳出以下几个关键的知识点: ### 1. Socket编程基础 #### 定义 Socket(套接字)是网络编程中的一个重要概念,它为应用程序提供了访问低层传输协议的能力,使得不同主机间的应用...

    selenium+pyton_google.rar

    标题 "selenium+pyton_google.rar" 暗示了这个压缩包可能包含了使用Python编程语言和Selenium库来操作Google浏览器的相关代码和教程。Selenium是一个强大的Web自动化测试工具,它允许开发者模拟用户行为,如点击、...

    协同过滤Pyton代码

    协同过滤是一种广泛应用于推荐系统中的机器学习算法,其主要原理是通过分析用户的历史行为来预测他们可能对哪些未接触过的项目感兴趣。在这个“协同过滤Python代码”中,我们可以期待找到一个实现这一算法的Python...

    pyton 实现学生信息管理系统

    在本项目中,"Python 实现学生信息管理系统"是一个初级编程练习,旨在帮助初学者掌握Python编程基础,特别是数据操作和文件处理。这个系统能够执行常见的数据库操作,如添加、删除、修改和查找学生信息。...

    pyton 创建对象 仅用于考试

    pyton 创建对象 仅用于考试

    Pyton_IOControl.rar_python gui_pyton

    需要工具: 1. Python 2.3 以上 2. BOA Constructor Python設定檔介面程式設計 這段程式碼主要是把資料儲存到config.txt這個檔案中,我們將資料以 \n[_config_]\n 來作區隔,以便將來將資料讀出來時可以知道所...

    pyton的帮助文档python-docs-html

    pyton的帮助文档python-docs-html

    Pyton数据类型,运算符和表达式

    一.常量,变量和标识符 1.标识符  用来表示各种程序成分,命名程序中的一些实体(变量,常量,函数名等)  标识符命名规则: (1)变量名和函数名中的英文字母一般用小写,增加程序的可读性 (2)见名知意(一般...

    Pyton与C语言的比较研究.pdf

    Pyton与C语言的比较研究.pdf Pyton与C语言是当前比较流行的两种高级程序设计语言,它们都是进行计算机算法描述的语言,在编程的算法与思路上有很多相同,但在某些地方具体实现上存在着差异。了解这些差异有利于加强...

    mysql for pyton 源代码

    MySQL for Python源代码是Python开发者用来与MySQL数据库进行交互的重要工具。这个2.0.0版本的源代码提供了丰富的功能,使Python程序员能够方便地在应用程序中集成数据库操作。通过理解并研究这些源代码,我们可以...

    a byte of pyton(python简明教程 3.0版本)

    《Python简明教程 3.0版本》是针对初学者精心编写的Python编程入门资料,旨在帮助新手快速掌握这门强大且广泛使用的编程语言。Python 3.0是Python语言的一个重要版本,它引入了许多改进和新特性,使得代码更加简洁、...

    pyton学习记录_python_源码

    "pyton学习记录_python_源码"这个标题表明这是一份关于Python编程的学习笔记,可能包含了作者在学习过程中的代码示例和理解。描述中提到笔记内容较为基础,非常适合初学者入门,这意味着它可能涵盖了Python的基础...

    pyton pyside 数字时钟

    非常有意思的python pyside小程序-数字时钟,让编程不无聊!

    Leo Jay Pyton2exe

    解开包后,只要用自己的程序替换mysrc.zip就可以使用了。 包里有runpy.exe和runpyw.exe两个文件。其中,runpy.exe是控制台程序,runpyw.exe是非控制台程序。这两个程序分别类似于python.exe和pythonw.exe。...

    pyton ursina 实现简陋我的世界

    在本项目"pyton ursina 实现简陋我的世界"中,我们看到的是一个尝试利用Ursina来构建一个简易版的Minecraft游戏。Minecraft是一款非常受欢迎的沙盒建造游戏,而这个项目则是其在Python环境下的一个小型实现。 首先...

    0基础pyton学习笔记

    新手可以利用资源进行学习

    pyton爬虫各种学习代码.zip

    本资源包"pyton爬虫各种学习代码.zip"包含了一系列的学习代码示例,旨在帮助初学者和进阶者深入理解Python爬虫的原理与实践。 1. **基础概念** - **爬虫**:程序模拟人类浏览网页的行为,自动抓取大量网络信息。 ...

    用Pyton编译的GDAL

    **正文** 标题:“用Python编译的GDAL” 在GIS(地理信息系统)领域,GDAL(Geospatial Data Abstraction Library)是一个强大的开源库,它提供了读取、写入和处理多种地理空间数据格式的能力。...

    pyton telnet自动备份交换机配置

    使用python编写的自动备份交换机配置的程序,单文件直接运行即可,目前只支持telnet方式连接交换机,支持华为、华三、锐捷交换机,通过tftp方式自动备份配置 管理信息表格为[管理信息.csv],和本程序放在同一个目录 ...

    使用pyton对OpenStreetMap地图数据进行清洗

    使用pyton对OpenStreetMap地图数据进行清洗 美国纽约 下载地址:https://www.openstreetmap.org/export#map=11/40.7241/-73.9689 选择纽约是想了解下纽约这个城 数据统计信息 1.文件大小 map.osm ......... ...

Global site tag (gtag.js) - Google Analytics