Socket Programming and simple REST api

This post will be a recap of how I did my assignment for tele3118 as a future reference.

It basically asks you to design a local server to display JSON data acquired from a remote server using UDP socket programming.

I did the first part which is sokcet programming with ease as it only requires to pull a series of string from remote server. The only problem I met was initially the test server was written in python2 so that it won’t recognized the message from client but it was solved by modifying the python file of test server.

For the second part it wasn’t as easy as google for a few examples. It consists of two task. First is to print out the list of names contained in the student list acquired from part one. Second is to design REST api for the user to pull specific student’s mark by entering the name.

1
2
3
4
5
6
7
8
9
10
11
12
@app.route('/api/studentlist', methods=['GET'])
def get_tasks():
return jsonify({'names': student})

@app.route('/api/studentmark/<string:search_name>', methods=['GET'])
def get_task(search_name):
b = [] #empty list
for name,mark in Marks.items():
if name == search_name:
b.append(name)
b.append(mark)
return jsonify(b)

It is quite self explanatory that if I typed localhost/api/studentlist, it will direct me to the page with all the names of students. And if I typed localhost/api/studentmark/Josh, it will show me the mark that associates with Josh.

This assignment also consists of a bonus part where a front-end interface is required rather then the plain webpage. So I used a html example of someone else for the mark searching part. For the simplicity of this post, I will just post the html screen shot of the final web page.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
from flask import Flask, request,render_template,url_for
from flask_restful import Resource, Api
from json import dumps
from flask import jsonify
import sys
from importlib import reload
import re
import json
import socket


reload(sys)
##sys.setdefaultencoding('utf8')
client = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
serverName = '149.171.37.161'
serverPort = 5000
msg = 'studentmarklist' + '\0'
msg = msg.encode()

client.sendto(msg,(serverName,serverPort))
response_msg,addr =client.recvfrom(1024)
msg_recv =response_msg.decode('utf-8')
client.close()

##TODO eliminate leading zero in marks
msg_recv = msg_recv[4:]
msg_recv=re.split('(\d+)',msg_recv)
msg_recv_name = msg_recv[1::2]
msg_recv_mark = msg_recv[::2]
msg_recv_mark = [s.strip('\x00') for s in msg_recv_mark]
msg_recv_mark = [s.lstrip('0') for s in msg_recv_mark]
zipbObj = zip(msg_recv_mark,msg_recv_name)
dictOfMarklist = dict(zipbObj)
Marks = dictOfMarklist
print(json.dumps(Marks, indent=2, separators=(', ', ': ')))
student = []
for key in dictOfMarklist:
student.append(key)

#### FLASK
app = Flask(__name__)
api = Api(app)

@app.route('/api/studentlist', methods=['GET'])
def get_tasks():
return jsonify({'names': student})

@app.route('/api/studentmark/<string:search_name>', methods=['GET'])
def get_task(search_name):
b = [] #empty list
for name,mark in Marks.items():
if name == search_name:
b.append(name)
b.append(mark)
return jsonify(b)

@app.route('/')
def helloworld():
#result = jsonify(student)
STUDENTNAME = json.dumps(student, indent=2, separators=(', ', ': '))
return render_template('test1.html',data = STUDENTNAME,MARKS = Marks)



if __name__ == '__main__':
app.run(debug=True)