This repository has been archived by the owner on Apr 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache_course.go
99 lines (90 loc) · 1.85 KB
/
cache_course.go
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package main
import (
"database/sql"
"encoding/json"
"log"
"strings"
"time"
_ "github.com/go-sql-driver/mysql"
"github.com/penn-automate/penn-opendata-api"
)
const (
maxRetry = 5
waitRetry = time.Second * 3
)
var db *sql.DB
func init() {
var err error
db, err = sql.Open("mysql", databaseLink)
if err != nil {
log.Fatal(err)
}
}
func encodeInstName(i opendata.CourseInstructor) string {
var b strings.Builder
b.WriteString(i.FirstName)
if i.MiddleInitial != nil {
b.WriteByte(' ')
b.WriteString(*i.MiddleInitial)
}
b.WriteByte(' ')
b.WriteString(i.LastName)
return b.String()
}
func main() {
api := opendata.NewOpenDataAPI(clientId, clientSecret).GetRegistrar()
stmt, e := db.Prepare("REPLACE INTO course_list_new VALUES(?,?,?,?,?,?)")
if e != nil {
log.Fatal(e)
}
count := 0
iterator := api.SearchCourseSection(map[string]string{"term": term})
outer:
for retry := 1; retry <= maxRetry; retry++ {
if retry != 1 {
time.Sleep(waitRetry)
} else {
time.Sleep(time.Second)
}
if !iterator.NextPage() {
break
}
for i := 0; i < iterator.GetPageSize(); i++ {
data := new(opendata.CourseSearchData)
err := iterator.GetResult(data, i)
if err != nil {
log.Print(err)
continue outer
}
insts := make([]string, 0, len(data.Instructors))
for _, inst := range data.Instructors {
insts = append(insts, encodeInstName(inst))
}
instData, e := json.Marshal(insts)
if e != nil {
log.Fatal(e)
}
_, e = stmt.Exec(
data.SectionId,
data.Term,
data.SectionTitle,
instData,
data.Activity,
([]byte)(iterator.GetRawData(i)),
)
if e != nil {
log.Println(e)
} else {
count++
}
}
retry = 0
log.Printf("Acquired in total %d listings.", count)
}
if err := iterator.GetError(); err != nil {
log.Print(err)
}
if e := stmt.Close(); e != nil {
log.Fatal(e)
}
}