-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
598 lines (475 loc) · 20.2 KB
/
Copy pathapp.py
File metadata and controls
598 lines (475 loc) · 20.2 KB
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
import os
import sys
import click
from datetime import datetime
from flask import Flask, render_template, request, redirect, url_for, flash, abort, session, jsonify
from flask_sqlalchemy import SQLAlchemy
WIN = sys.platform.startswith('win')
if WIN: # If it's a Windows system, use three slashes
prefix = 'sqlite:///'
else: # Otherwise, use four slashes
prefix = 'sqlite:////'
app = Flask(__name__, template_folder='templates')
app.config['DEBUG'] = True
app.config['SECRET_KEY'] = 'BW1002'
app.config['SQLALCHEMY_DATABASE_URI'] = prefix + os.path.join(app.root_path, 'data.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # Disable modification tracking for models
app.jinja_env.filters['datetimeformat'] = lambda value, formative='%Y-%m-%d %H:%M:%S': value.strftime(formative)
db = SQLAlchemy(app) # Initializing the SQLAlchemy extension
# Define the user class
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
password = db.Column(db.String(80), nullable=False)
role = db.Column(db.String(20), default='user')
def is_admin(self):
return self.role == 'admin'
job_applicant = db.Table('job_applicant',
db.Column('job_id', db.Integer, db.ForeignKey('job.id'), primary_key=True),
db.Column('applicant_name', db.String(30), db.ForeignKey('applicant.name'), primary_key=True)
)
# Define the job class
class Job(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(50), unique=True)
money = db.Column(db.Integer)
amount = db.Column(db.Integer)
date = db.Column(db.Date)
description = db.Column(db.Text, nullable=True)
applicants = db.relationship('Applicant', secondary=job_applicant, back_populates='jobs')
# Define the applicant class
class Applicant(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(30), unique=False)
age = db.Column(db.Integer)
score = db.Column(db.Integer)
major = db.Column(db.String(30))
vocation = db.Column(db.String(30))
date = db.Column(db.Date)
description = db.Column(db.Text, nullable=True)
jobs = db.relationship('Job', secondary=job_applicant, back_populates='applicants')
class UserLog(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), nullable=False)
action_type = db.Column(db.String(20), nullable=False) # 操作类型,如申请或发布
job_name = db.Column(db.String(50)) # 岗位名称
timestamp = db.Column(db.DateTime, default=datetime.utcnow)
def __init__(self, username, action_type, job_name=None):
self.username = username
self.action_type = action_type
self.job_name = job_name
@app.cli.command()
@click.option('--drop', is_flag=True, help='Create after drop.')
def initdb(drop):
"""Initialize the database."""
if drop:
db.drop_all()
db.create_all()
# 设置预存数据
sample_jobs = [
Job(title='软件工程师', money=15000, amount=1000, date=datetime.now(), description='软件开发'),
Job(title='网页工程师', money=9000, amount=500, date=datetime.now(), description='网页开发'),
Job(title='数据工程师', money=11000, amount=600, date=datetime.now(), description='数据管理'),
Job(title='测试工程师', money=8000, amount=500, date=datetime.now(), description='算法测试'),
Job(title='系统管理员', money=10000, amount=1200, date=datetime.now(), description='维护服务器'),
Job(title='网络工程师', money=13000, amount=1800, date=datetime.now(), description='实施和管理计算机网络'),
Job(title='前端工程师', money=12000, amount=1200, date=datetime.now(), description='专注于用户界面和用户体验'),
Job(title='后端工程师', money=13000, amount=1800, date=datetime.now(), description='处理应用程序的服务器端逻辑'),
]
sample_applicant = [
Applicant(name='张三', age=24, score=80, major='计算机科学', vocation='系统管理员', date=datetime.now(),
description='熟练掌握C++'),
Applicant(name='李四', age=27, score=50, major='大数据科学', vocation='数据工程师', date=datetime.now(),
description='擅长mySQL'),
Applicant(name='王五', age=25, score=70, major='软件工程', vocation='软件工程师', date=datetime.now(),
description='擅于qt开发'),
Applicant(name='陈六', age=24, score=60, major='电子信息', vocation='网络工程师', date=datetime.now(), description='熟悉硬件')
]
# 设置管理员账号
# admin_user = User(username='wbl', password='wbl20031002', role='admin')
# db.session.add(admin_user)
db.session.add_all(sample_jobs)
db.session.add_all(sample_applicant)
# 为每个申请者根据其 vocation 选择合适的工作
for applicant in sample_applicant:
for job in sample_jobs:
if applicant.vocation == job.title:
applicant.jobs.append(job)
db.session.commit()
click.echo('Database initialized!')
@app.errorhandler(404)
def page_not_found(_):
"""Error handler for 404 page not found."""
return render_template('404.html'), 404
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
user_type = request.form['userType']
# 检查数据库中是否存在相同的用户名
existing_user = User.query.filter_by(username=username).first()
if existing_user:
# 如果用户名已存在,显示一条消息并重新渲染注册表单
flash('该用户名已被占用!', 'danger')
return render_template('register.html')
# 用户名未被占用,继续注册流程
user = User(username=username, password=password, role=user_type)
db.session.add(user)
db.session.commit()
flash('注册成功!', 'success')
return redirect(url_for('login'))
return render_template('register.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
user = User.query.filter_by(username=username, password=password).first()
if user:
session['user_id'] = user.id
session['username'] = user.username
session['role'] = user.role
return redirect(url_for('index'))
else:
flash('登录失败,请检查您的用户名和密码。', 'danger')
return render_template('login.html')
@app.route('/logout')
def logout():
# 删除 session 中的用户信息
session.pop('user_id', None)
session.pop('username', None)
session.pop('role', None)
return redirect(url_for('login'))
@app.route('/change_password', methods=['GET', 'POST'])
def change_password():
if 'user_id' not in session:
flash('请先登录。', 'danger')
return redirect(url_for('login'))
if request.method == 'POST':
old_password = request.form['old_password']
new_password = request.form['new_password']
user = User.query.get(session['user_id'])
# 确认旧密码是否正确
if user and user.password == old_password:
user.password = new_password
db.session.commit()
flash('密码已成功更改!', 'success')
return redirect(url_for('index'))
else:
flash('原密码不正确。', 'danger')
return render_template('change_password.html')
@app.route('/all_user')
def all_user():
users = User.query.all()
return render_template('all_user.html', users=users)
@app.route('/edit_user/<int:user_id>', methods=['GET', 'POST'])
def edit_user(user_id):
user = User.query.get_or_404(user_id)
if request.method == 'POST':
# 更新用户信息的逻辑
return redirect(url_for('all_user'))
return render_template('edit_user.html', user=user)
@app.route('/delete_user/<int:user_id>', methods=['POST'])
def delete_user(user_id):
user = User.query.get_or_404(user_id)
db.session.delete(user)
db.session.commit()
flash('用户已删除')
return redirect(url_for('all_user'))
@app.route('/')
def index():
jobs = Job.query.all()
applicant = Applicant.query.all()
return render_template('index.html', jobs=jobs, applicants=applicant)
@app.route('/viewlist', methods=['GET', 'POST'])
def viewlist():
jobs = Job.query.all()
return render_template('viewlist.html', jobs=jobs)
@app.route('/viewlist/viewmoney_asc')
def viewmoney_asc():
jobs = Job.query.all()
sorted_jobs = sorted(jobs, key=lambda x: x.amount, reverse=False)
return render_template('viewlist.html', jobs=sorted_jobs)
@app.route('/viewlist/viewmoney_desc')
def viewmoney_desc():
jobs = Job.query.all()
sorted_jobs = sorted(jobs, key=lambda x: x.amount, reverse=True)
return render_template('viewlist.html', jobs=sorted_jobs)
@app.route('/viewlist/<int:job_id>', methods=['POST'])
def viewlist_delete(job_id):
job = Job.query.get_or_404(job_id)
# 获取所有申请这个工作的申请者
applicants_to_delete = Applicant.query.filter(
Applicant.jobs.any(id=job_id)
).all()
# 删除所有相关的申请者信息
for applicant in applicants_to_delete:
db.session.delete(applicant)
# 删除工作本身
db.session.delete(job)
db.session.commit()
flash('岗位及相关申请已删除!')
return redirect(url_for('viewlist'))
@app.route('/add_job', methods=['GET', 'POST'])
def add_job():
if request.method == 'POST':
title = request.form.get('title')
money = request.form.get('money')
amount = request.form.get('amount')
description = request.form.get('description')
date = datetime.now()
# 检查是否已存在相同名称的职位
existing_job = Job.query.filter_by(title=title).first()
if existing_job:
return jsonify({"error": "相同名称的职位已存在,请使用不同的名称。"}), 400
new_job = Job(title=title, money=money, amount=amount, description=description, date=date)
db.session.add(new_job)
db.session.commit()
if 'user_id' in session:
new_user_log = UserLog(username=session['username'], action_type='添加', job_name=title)
db.session.add(new_user_log)
db.session.commit()
# Returning result
return jsonify({"success": "新职位已成功添加"}), 200
else:
return render_template('add_job.html')
@app.route('/edit_job/<int:job_id>', methods=['GET', 'POST'])
def edit_job(job_id):
job = Job.query.get_or_404(job_id)
if not job:
abort(404)
if request.method == 'POST':
new_title = request.form.get('title', '')
new_money = request.form.get('money', '')
new_amount = int(request.form.get('amount', 0))
new_description = request.form.get('description', '')
# 先检查是否有重复的职位标题
existing_job = Job.query.filter(Job.id != job_id, Job.title == new_title).first()
if existing_job:
return jsonify({"error": "相同名称的职位已存在,请使用不同的名称。"}), 400
# 没有重复的情况下更新 job
job.title = new_title
job.money = new_money
job.amount = new_amount
job.description = new_description
new_applicants = Applicant.query.filter_by(vocation=job.title).all()
# 更新岗位的申请者关联
job.applicants = new_applicants
if 'user_id' in session:
new_user_log = UserLog(username=session['username'], action_type='编辑', job_name=new_title)
db.session.add(new_user_log)
db.session.commit()
# 保存到数据库
db.session.commit()
return jsonify({"success": "职位信息已成功修改"}), 200
else:
return render_template('edit_job.html', job=job)
@app.route('/applylist', methods=['GET', 'POST'])
def applylist():
jobs = Job.query.with_entities(Job.title).distinct().all()
user_type = session.get('role')
username = session.get('username', None)
if user_type == 'admin':
applicants = Applicant.query.all()
else:
applicants = Applicant.query.filter_by(name=username).all()
return render_template('applylist.html', jobs=jobs, applicants=applicants)
@app.route('/applylist/applylist_asc')
def applylist_asc():
jobs = Job.query.with_entities(Job.title).distinct().all()
applicants = Applicant.query.all()
sorted_apply = sorted(applicants, key=lambda x: x.score, reverse=False)
return render_template('applylist.html', jobs=jobs, applicants=sorted_apply)
@app.route('/applylist/applylist_desc')
def applylist_desc():
jobs = Job.query.with_entities(Job.title).distinct().all()
applicants = Applicant.query.all()
sorted_apply = sorted(applicants, key=lambda x: x.score, reverse=True)
return render_template('applylist.html', jobs=jobs, applicants=sorted_apply)
school_scores = {
"一本": 10,
"211": 20,
"985": 30,
"海外qs30": 30,
"海外qs100": 10,
"其他": 0
}
education_scores = {
"高中": 0,
"专科": 10,
"本科": 20,
"硕士": 30,
"博士": 40
}
experience_scores = {
"无": 0,
"0-2年": 5,
"2-5年": 10,
"5-10年": 15,
"10年以上": 20
}
@app.route('/add_apply', methods=['GET', 'POST'])
def add_apply():
if request.method == 'POST':
# Fetching data from form
name = request.form.get('name', '')
age = int(request.form.get('age', 0)) # Convert age to integer
major = request.form.get('major', '')
vocation = request.form.get('vocation', '')
description = request.form.get('description', '')
# Fetching and calculating score-related data
school = request.form.get('school', '')
education = request.form.get('education', '')
experience = request.form.get('experience', '')
# 查询数据库,检查是否已存在相同姓名和意向岗位的申请
existing_applicant = Applicant.query.filter_by(name=name, vocation=vocation).first()
if existing_applicant:
return jsonify({"error": "请勿重复申请同一个岗位"}), 400
# Determine age score based on age range
if 20 <= age <= 25:
age_score = 10
elif 26 <= age <= 30:
age_score = 8
elif 31 <= age <= 35:
age_score = 5
else:
age_score = 0
total_score = (
school_scores.get(school, 0) +
education_scores.get(education, 0) +
experience_scores.get(experience, 0) +
age_score
)
# Creating a new applicant
new_applicant = Applicant(
name=name,
age=age,
score=total_score,
major=major,
vocation=vocation,
date=datetime.now(),
description=description
)
selected_job_title = request.form.get('vocation', '')
selected_job = Job.query.filter_by(title=selected_job_title).first()
new_applicant.jobs.append(selected_job)
# 保存到数据库
db.session.add(new_applicant)
db.session.commit()
if 'user_id' in session:
new_user_log = UserLog(username=session['username'], action_type='申请', job_name=selected_job.title)
db.session.add(new_user_log)
db.session.commit()
# Returning result
return jsonify({"success": "申请已提交"}), 200
else:
jobs = Job.query.all()
return render_template('add_apply.html', jobs=jobs)
@app.route('/edit_apply/<int:applicant_id>', methods=['GET', 'POST'])
def edit_apply(applicant_id):
applicant = Applicant.query.get_or_404(applicant_id)
if not applicant:
abort(404)
if request.method == 'POST':
name = request.form.get('name', '')
age = int(request.form.get('age', 0)) # Convert age to integer
major = request.form.get('major', '')
vocation = request.form.get('vocation', '')
description = request.form.get('description', '')
# Fetching and calculating score-related data
school = request.form.get('school', '')
education = request.form.get('education', '')
experience = request.form.get('experience', '')
# 查询数据库,检查是否已存在相同姓名和意向岗位的申请
existing_applicant = Applicant.query.filter(
Applicant.id != applicant_id,
Applicant.name == name,
Applicant.vocation == vocation
).first()
if existing_applicant:
return jsonify({"error": "请勿重复申请同一个岗位"}), 400
# Determine age score based on age range
if 20 <= age <= 25:
age_score = 10
elif 26 <= age <= 30:
age_score = 8
elif 31 <= age <= 35:
age_score = 5
else:
age_score = 0
total_score = (
school_scores.get(school, 0) +
education_scores.get(education, 0) +
experience_scores.get(experience, 0) +
age_score
)
applicant.name = name
applicant.age = age
applicant.major = major
applicant.vocation = vocation
applicant.description = description
applicant.score = total_score
db.session.commit()
# 更新岗位关联
selected_job_title = request.form.get('vocation', '')
selected_job = Job.query.filter_by(title=selected_job_title).first()
# 清除现有的岗位关联
applicant.jobs.clear()
# 添加新的岗位关联
if selected_job:
applicant.jobs.append(selected_job)
if 'user_id' in session:
new_user_log = UserLog(username=session['username'], action_type='修改', job_name=vocation)
db.session.add(new_user_log)
db.session.commit()
# 保存到数据库
db.session.commit()
return jsonify({"success": "申请已修改"}), 200
else:
jobs = Job.query.all()
return render_template('edit_apply.html', jobs=jobs, applicant=applicant)
@app.route('/delete_apply/<int:applicant_id>', methods=['POST'])
def delete_apply(applicant_id):
applicant = Applicant.query.get_or_404(applicant_id)
# 从所有相关工作中移除这个申请
for job in applicant.jobs:
job.applicants.remove(applicant)
# 删除申请本身
db.session.delete(applicant)
db.session.commit()
flash('申请已删除!')
return redirect(url_for('applylist'))
@app.route('/applicant_jobs')
def applicant_jobs():
user_type = session.get('role')
if user_type == 'admin':
applicants = Applicant.query.all()
else:
user_name = session.get('username', None)
applicants = Applicant.query.filter_by(name=user_name).all() if user_name else []
return render_template('applicant_jobs.html', applicants=applicants, user_type=user_type)
@app.route('/job_applicants')
def job_applicants():
jobs = Job.query.all()
return render_template('job_applicants.html', jobs=jobs)
@app.route('/user_log')
def user_log():
user_logs = UserLog.query.all()
return render_template('user_log.html', user_logs=user_logs)
@app.route('/delete_uselog/<int:user_log_id>', methods=['POST'])
def delete_uselog(user_log_id):
# 根据用户日志的唯一标识符查找相应的用户日志记录
user_logs = UserLog.query.get(user_log_id)
if user_logs:
# 如果找到用户日志记录,就从数据库中删除它
db.session.delete(user_logs)
db.session.commit()
flash('用户日志已删除')
else:
flash('未找到用户日志记录')
# 重定向回用户日志页面
return redirect(url_for('user_log'))
if __name__ == '__main__':
app.run(port=6688, debug=True)
# flask initdb --drop