首页 文章 精选 留言 我的

精选列表

搜索[基础软件],共10000篇文章
优秀的个人博客,低调大师

Jenkins CI持续集成项目基础配置

1. 安装Jenkins sudo wget -O /etc/yum.repos.d/jenkins.repo \ https://pkg.jenkins.io/redhat-stable/jenkins.repo sudo rpm --import https://pkg.jenkins.io/redhat-stable/jenkins.io.key sudo yum upgrade sudo yum install epel-release java-11-openjdk-devel sudo yum install jenkins sudo systemctl daemon-reload 引用自:https://www.jenkins.io/doc/book/installing/linux/#red-hat-centos 2. 打开http://ip:8080 按提示操作,并安装推荐插件 3. Jenkins安装插件 ① Git 插件 ② Docker 插件 ③ Kubernetes ④ Kubernetes Cli ⑤ Config File Provider ⑥ Pipeline Utility Steps 4. Jenkins服务器安装 maven git docker jdk(安装jenkins时已经启动) 5. 配置Credentials添加证书从git上拉代码 Jenkins服务器生成密钥: ssh-keygen -t rsa -C "ci@huanke.com" 使用阿里云的codeup的话,先创建个拉取的ram账户(例如:ci),在codeup中将ram账户ci给授权为开发权限。 然后阿里云登陆ci账户,上传服务器的id_rsa.pub 到codeup仓库的ci个人设置下的ssh公钥,并设置为只读权限。 最后Jenkins设置git拉去代码凭据

优秀的个人博客,低调大师

Flask框架基础全面教程(2021实战版)

环境 centos7python3.6 环境部署 yum install python3pip3 install flask 项目创建 mkdir newprojcd newproj # cat > Hello_development.py <<EOF ###开发模式 from flask import Flask app = Flask(__name__) app.debug = True ##开启是可以实时查看 @app.route('/') def hello_world(): return 'Hello World' if __name__ == '__main__': app.run('0.0.0.0',5000) EOF # cat > Hello_production.py <<EOF ###生产模式 from flask import Flask from wsgiref.simple_server import make_server app = Flask(__name__) @app.route('/') def hello_world(): return "hello" @app.route('/web') def hello_world2(): return "hello web" if __name__ == '__main__': server = make_server('0.0.0.0', 5000, app) server.serve_forever() EOF # python3 Hello_production.py 浏览器访问http://ip:5000 Flask 路由 @app.route('/hello') def hello_world(): return 'hello world' http://localhost5000/hello Flask 变量规则 from flask import Flask app = Flask(__name__) @app.route('/hello/<name>') ##字符串变量 def hello_name(name): return 'Hello %s!' % name @app.route('/blog/<int:postID>') ##int型变量 def show_blog(postID): return 'Blog Number %d' % postID @app.route('/rev/<float:revNo>') ##浮点型变量 def revision(revNo): return 'Revision Number %f' % revNo if __name__ == '__main__': app.run(debug = True) 打开浏览器并输入URL http://localhost:5000/hello/feko如果输入http://localhost:5000/hello/feko/ 就会报404 规范URL Flask的URL规则基于Werkzeug的路由模块。这确保形成的URL是唯一的,并且基于Apache规定的先例。 from flask import Flask app = Flask(__name__) @app.route('/hello/<name>/') ##字符串变量 def hello_name(name): return 'Hello %s!' % name @app.route('/blog/<int:postID>/') ##int型变量 def show_blog(postID): return 'Blog Number %d' % postID @app.route('/rev/<float:revNo>/') ##浮点型变量 def revision(revNo): return 'Revision Number %f' % revNo if __name__ == '__main__': app.run(debug = True) 打开浏览器并输入URL http://localhost:5000/hello/feko或 http://localhost:5000/hello/feko/ 都不会报错 Flask URL构建 URL重定向 from flask import Flask, redirect, url_for app = Flask(__name__) @app.route('/admin/') def hello_admin(): return 'Hello Admin' @app.route('/guest/<guest>/') def hello_guest(guest): return 'Hello %s as Guest' % guest @app.route('/user/<name>/') def hello_user(name): if name =='admin': return redirect(url_for('hello_admin')) else: return redirect(url_for('hello_guest',guest = name)) if __name__ == '__main__': app.run(debug = True) 打开浏览器并输入URL - http://localhost:5000/user/admin浏览器中的应用程序响应是:Hello Admin在浏览器中输入以下URL - http://localhost:5000/user/feko 应用程序响应现在更改为:Hello feko as Guest HTTP方法 GET - 从指定的资源请求数据。以未加密的形式将数据发送到服务器。最常见的方法。POST - 向指定的资源提交要被处理的数据,用于将HTML表单数据发送到服务器。login.html <html> <body> <form action = "http://192.168.209.211:5000/login/" method = "post"> <p>Enter Name:</p> <p><input type = "text" name = "nm" /></p> <p><input type = "submit" value = "submit" /></p> </form> </body> </html> Hello_development.py from flask import Flask, redirect, url_for, request app = Flask(__name__) @app.route('/success/<name>/') def success(name): return 'welcome %s' % name @app.route('/login/',methods = ['POST', 'GET']) ##action 地址要对应,有'/'也有'/' def login(): if request.method == 'POST': user = request.form['nm'] return redirect(url_for('success',name = user)) else: user = request.args.get('nm') return redirect(url_for('success',name = user)) if __name__ == '__main__': app.run(debug = True) Flask 模板使用 render_template 函数用于渲染模板模板必须放在templates目录下Hello_development.py from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): my_int = 1 my_str = 'fafa' my_list = [1,2,3,4,5,6] my_dict = { 'name': 'feko', 'age': 26 } # render_template方法:渲染模板 # 参数1: 模板名称 参数n: 传到模板里的数据 return render_template('hello.html', my_int=my_int, my_str=my_str, my_list=my_list, my_dict=my_dict ) if __name__ == '__main__': app.run(debug=True) cat templates/hello.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h3>我是模板</h3> {{ my_int }} <br> {{ my_str }} <br> {{ my_list }} <br> {{ my_dict }} <hr> <h3>两种方法:模板的list数据获取</h3> <hr> {{ my_list[0] }} <br> {{ my_list.1 }} <hr> <h3>两种方法:字典数据获取</h3> <hr> {{ my_dict['name'] }} <br> {{ my_dict.age }} <hr> <h3>两种方法:算术运算</h3> <br> {{ my_list.0 + 10 }} <br> {{ my_list[0] + my_list.1 }} </body> </html> Flask 静态文件静态文件主要包括js/css文件,并存在static目录下python程序去渲染html模板,模板再去调用js里面的函数Hello_development.py from flask import Flask, render_template app = Flask(__name__) @app.route("/") def index(): return render_template("index.html") if __name__ == '__main__': app.run(debug = True) templates/index.html <html> <head> <script type = "text/javascript" src = "{{ url_for('static', filename = 'hello.js') }}" ></script> </head> <body> <input type = "button" onclick = "sayHello()" value = "Say Hello" /> </body> </html> static/hello.js function sayHello() { alert("Hello World") } #Flask Request对象来自客户端网页的数据作为全局请求对象发送到服务器。为了处理请求数据,应该从Flask模块导入。Request对象的重要属性如下所列:Form - 它是一个字典对象,包含表单参数及其值的键和值对。args - 解析查询字符串的内容,它是问号(?)之后的URL的一部分。Cookies - 保存Cookie名称和值的字典对象。files - 与上传文件有关的数据。method - 当前请求方法。 Flask 将表单数据发送到模板 cat Hello_development.py ##主程序 from flask import Flask, render_template, request app = Flask(__name__) @app.route('/') def student(): return render_template('student.html') @app.route('/result',methods = ['POST','GET']) def result(): if request.method == 'POST': result = request.form return render_template('result.html',result = result) if __name__ == '__main__': app.run('0.0.0.0',5000,debug = True) cat templates/student.html ##脚本 <form action="http://192.168.209.211:5000/result" method="POST"> <p>Name <input type = "text" name = "Name"/></p> <p>Physics <input type = "text" name = "Physics"/></p> <p>Maths <input type = "text" name = "Maths"/></p> <p><input type = "submit" value="submit"/></p> </form> cat templates/result.html ##模板 <!doctype html> <table border = 1> {% for key, value in result.items() %} <tr> <th>{{key}}</th> <th>{{value}}</th> </tr> {% endfor %} </table> Flask Cookies Cookie以文本文件的形式存储在客户端的计算机上。其目的是记住和跟踪与客户使用相关的数据,以获得更好的访问者体验和网站统计信息。Hello_development.py from flask import Flask, make_response, request app = Flask(__name__) @app.route('/set_cookies') def set_cookies(): resp = make_response("success") resp.set_cookie("cookie_id_1","009911", max_age=3600) return resp @app.route('/get_cookies') def get_cookies(): cookies_get = request.cookies.get('cookie_id_1') return cookies_get @app.route('/delete_cookies') def delete_cookies(): resp = make_response('del success') resp.delete_cookie('cookie_id_1') return resp if __name__ == '__main__': app.run('0.0.0.0',5000,debug=True) Flask Sessions(会话) Session(会话)数据存储在服务器上。会话是客户端登录到服务器并注销服务器的时间间隔。会话变量使用cat Hello_development.py #!/usr/bin/env ptyoh # ~*~ coding: utf-8 ~*~ from flask import Flask, session, redirect, url_for, escape, request app = Flask(__name__) app.secret_key = '9988aabbkkllii' @app.route('/') def index(): if 'username' in session: return "登录用户是:" + session["username"] + "<br><a href='/logout'>点击这里注销登录</a>" return ''' 你暂时没有登录 <br> <a href='/login'>点击这里登录</a> ''' @app.route('/login',methods = ['POST','GET']) def login(): if request.method == 'POST': session["username"] = request.form["username"] ##可以直接当作dict使用 return redirect(url_for('index')) return ''' <form action = '' method = 'POST'> <p>username:<input type='text' name = 'username' <br></p> <p><input type='submit' value = 'submit'</p> </form> ''' @app.route('/logout') def logout(): session.pop('username',None) return redirect(url_for('index')) if __name__ == '__main__': app.run('0.0.0.0',5000,debug = True) Flask 重定向和错误 重定向Flask.redirect(location, statuscode, response)在上述函数中:location参数是应该重定向响应的URL。statuscode发送到浏览器标头,默认为302。response参数用于实例化响应。错误Flask类具有带有错误代码的abort()函数。 Flask.abort(code)code参数采用以下值之一:400 - 用于错误请求401 - 用于未身份验证的403 - Forbidden404 - 未找到406 - 表示不接受415 - 用于不支持的媒体类型429 - 请求过多 Hello_development.py #!/usr/bin/env ptyoh # ~*~ coding: utf-8 ~*~ from flask import Flask, session, redirect, url_for, escape, request,render_template,abort app = Flask(__name__) @app.route('/') def index(): return render_template('log_in.html') @app.route('/login',methods = ['POST','GET']) def login(): if request.method == 'POST': if request.form["username"] == "admin": return redirect(url_for('success'),301) else: abort(401) else: return redirect(url_for('index')) @app.route('/success') def success(): return "login is success" if __name__ == '__main__': app.run('0.0.0.0',5000,debug = True) templates/log_in.html <form action="/login" method="post" > <p>username:<input type="text" name="username"/></p> <p><input type="submit" value="submit"/></p> </form> Flask 消息闪现 一个好的基于 GUI 的应用程序会向用户提供有关交互的反馈。简单使用:后端定义flash("login successful!!")模板获取get_flashed_messages() Hello_development.py #!/usr/bin/env ptyoh # ~*~ coding: utf-8 ~*~ from flask import Flask, session, redirect, url_for, escape, request,render_template,abort,flash import os app = Flask(__name__) app.secret_key=os.urandom(32) @app.route('/') def index(): return render_template('index.html') @app.route('/login',methods = ['POST','GET']) def login(): error = None if request.method == 'POST': if request.form['username'] != "admin" or request.form['password'] != "admin": error = "Invalid username or passworld!!!" else: flash("login is successful!!!") return redirect(url_for('index')) return render_template('login.html',error = error) if __name__ == '__main__': app.run('0.0.0.0',5000,debug = True) templates/index.html <html> <head> <meta charset="UTF-8"> <title>Index</title> </head> <body> {% with messages = get_flashed_messages() %} {% if messages %} {% for i in messages %} {{i}} {% endfor %} {% endif %} {% endwith %} <p>Do you want to <a href="{{ url_for('login') }}">log in?</a></p> </body> </html> templates/login.html <html> <head> <meta charset="UTF-8"> <title>Login</title> </head> <body> <form action="/login" method="post"> <p>username:<input type="text" name="username"/></p> <p>password:<input type="text" name="password"/></p> <p><input type="submit" value="submit"/></p> </form> {% if error %} <p>ERROR:{{error}}</p> {% endif %} </body> </html> Flask 文件上传 在 Flask 中处理文件上传非常简单。它需要一个 HTML 表单,其 ​enctype​ 属性设置为“​multipart / form-data”​,将文件发布到 URL。URL 处理程序从 ​request.files[]​ 对象中提取文件,并将其保存到所需的位置。 Hello_development.py #!/usr/bin/env ptyoh # ~*~ coding: utf-8 ~*~ from flask import Flask, request,render_template from werkzeug.utils import secure_filename import os app = Flask(__name__) app.config['UPLOAD_FOLDER'] = 'upload/' @app.route('/upload') def upload(): return render_template('upload.html') @app.route('/upload_file',methods = ['POST','GET']) def upload_file(): if request.method == 'POST': f = request.files["file"] f.save(os.path.join(app.config['UPLOAD_FOLDER'],secure_filename(f.filename))) return "upload file is successful!!!" if __name__ == '__main__': app.run('0.0.0.0',5000,debug = True) templates/upload.html <html> <head> <meta charset="UTF-8"> <title>file upload</title> </head> <form action="/upload_file" method="post" enctype="multipart/form-data"> <p><input type="file" name="file" accept=".jpg,.png,.zip,.tar.gz"/> <input type="submit" value="submit"/></p> <p>注意:上传的文件名默认不支持中文命名</p> </form> </html> Flask扩展 Flask通常被称为微框架,因为核心功能包括基于Werkzeug的WSGI和路由以及基于Jinja2的模板引擎。此外,Flask框架还支持cookie和会话,以及JSON,静态文件等Web帮助程序。这不足以开发完整的Web应用程序。Flask扩展为Flask框架提供了可扩展性。Flask扩展是一个Python模块重要的Flask扩展:Flask Mail - 为Flask应用程序提供SMTP接口Flask WTF - 添加WTForms的渲染和验证Flask SQLAlchemy - 为Flask应用程序添加SQLAlchemy支持Flask Sijax - Sijax的接口 - Python/jQuery库,使AJAX易于在Web应用程序中使用 Flask扩展之邮件 Flask-Mail扩展使得与任何电子邮件服务器建立简单的接口变得非常容易,属于python模块,可以用pip安装。使用Mail类来配置邮箱和发送邮件,Message类来封装邮件.测试账号jkfeko94@163.combr/>使用Mail类来配置邮箱和发送邮件,Message类来封装邮件.测试账号jkfeko94@163.comjkfeko9488889999 #密码WGPJPPBTONSIQKCE # Hello_development.py from flask import Flask from flask_mail import Mail,Message app= Flask(__name__) ##定义邮件配置 app.config['MAIL_SERVER'] = 'smtp.163.com' app.config['MAIL_PORT'] = 465 app.config['MAIL_USERNAME'] = 'jkfeko94@163.com' app.config['MAIL_PASSWORD'] = 'WGPJPPBTONSIQKCE' app.config['MAIL_USE_TLS'] = False app.config['MAIL_USE_SSL'] = True ##创建实例 mail = Mail(app) @app.route('/') def index(): msg = Message('Flask Mail',sender=app.config['MAIL_USERNAME'],recipients=['1025158107@qq.com']) msg.body = "This is a flask mail send test.." mail.send(msg) return 'sent' if __name__ == '__main__': app.run('0.0.0.0',5000,debug=True) Flask扩展之WTF WTForms表单:Web应用程序的一个重要方面是为用户提供用户界面的扩展。如果通过html创建表单:表单元素必须定义两次 - 一次在HTML中,另一次在服务器端脚本中。用WTF就只创建一次即可。WTF两大部分wtforms标准表单字段:如 TextField 表示<input type ='text'> ##HTML表单元素validators验证器:如validators.DataRequired("不能为空") ##不输入会返回error="不能为空" forms.py from flask_wtf import FlaskForm from wtforms import RadioField,TextAreaField,SelectField,IntegerField,SubmitField,StringField from wtforms import validators, ValidationError import email_validator ##创建联系人的类,包括名字,性别,地址,邮箱,年龄,技能语言 ##用到WTF 必须继承FlaskForm类 class ContactForm(FlaskForm): name = StringField('姓名',[validators.DataRequired('姓名不能为空,请输入正常的名字!!!')]) gender = RadioField('性别',choices=[('M','男'),('F','女')]) address = TextAreaField("住址") email = StringField('邮箱',[validators.DataRequired('邮箱不能为空!!'),validators.Email("邮箱格式错误,请输入正确格式")]) age = IntegerField('年龄') language = SelectField('编程语言',choices=[('cpp','C++'),('py','python')]) submit = SubmitField('提交') Hello_development.py from flask import Flask,render_template,request,flash from forms import ContactForm import os app = Flask(__name__) app.secret_key = os.urandom(32) @app.route('/contact',methods=['POST','GET']) def contact(): form = ContactForm() #实例化联系人表单 if request.method == 'POST': if form.validate() == False: ##检查表单输入是否有误 flash("输入内容有误") return render_template('contact.html', form=form) else: name = form.name.data ##获取表单值 gender = form.gender.data email = form.email.data age = form.age.data language = form.language.data return str(name) + "<br>" + \ str(gender) + "<br>" +\ str(email) + "<br>" +\ str(age) + "<br>" +\ str(language) + "<br>" +\ "<br> post contact is successful!!!" return render_template('contact.html',form = form) if __name__ == "__main__": app.run('0.0.0.0',5000,debug=True) templates/contact.html <html> <head> <meta charset="UTF-8"/> <title>联系人表单填写</title> </head> <body> <h1>联系人表单填写 </h1> {% with msg = get_flashed_messages() %} {% if msg %} {% for i in msg %} {{ i }} {% endfor %} {% endif %} {% endwith %} {% for msg in form.name.errors %} <div>{{ msg }}</div> {% endfor %} {% for msg in form.email.errors %} <div>{{ msg }}</div> {% endfor %} {% for msg in form.age.errors %} <div>{{ msg }}</div> {% endfor %} <form action="/contact" method="post"> <fieldset> <legend>联系人表单填写内容</legend> <!-- 渲染所有隐藏字段,包括跨站请求伪造保护 --> {{ form.hidden_tag() }} <div style=" font-size:20px;font-weight:bold; margin-left: 600px;"> {{ form.name.label }} <br> {{ form.name }} <br> {{ form.gender.label }} {{ form.gender }} <br> {{ form.address.label }} <br> {{ form.address }} <br> {{ form.email.label }} <br> {{ form.email }} <br> {{ form.age.label }} <br> {{ form.age }} <br> {{ form.language.label }} <br> {{ form.language }} <br> {{ form.submit }} </div> </fieldset> </form> </body> </html> Flask扩展之SQLite3 创建sqlite数据库和表Create_Sqlite.py import sqlite3 con = sqlite3.connect('database.db') cur = con.cursor() cur.execute('create table contact (name TEXT, gender TEXT, email TEXT, age TEXT, language TEXT)') con.commit() con.close() Hello_development.py from flask import Flask,render_template,request,flash from forms import ContactForm import sqlite3 import os app = Flask(__name__) app.secret_key = os.urandom(32) @app.route('/') def home(): return render_template('home.html') @app.route('/contact',methods=['POST','GET']) def contact(): form = ContactForm() #实例化联系人表单 if request.method == 'POST': if form.validate() == False: ##检查表单输入是否有误 flash("输入内容有误") return render_template('contact.html', form=form) else: try: name = form.name.data gender = form.gender.data email = form.email.data age = form.age.data language = form.language.data with sqlite3.connect("database.db") as con: ##要先手动创建sqlite数据库和表 cur = con.cursor() cont = [(name,gender,email,age,language)] cur.executemany('INSERT INTO contact(name,gender,email,age,language) VALUES (?,?,?,?,?)', cont) con.commit() msg = "Record successfully added." except: con.rollback() #msg = "error record is fail." finally: con.close() return render_template('result.html',msg = msg) return render_template('contact.html',form = form) @app.route('/show') def show(): with sqlite3.connect("database.db") as con: ##要先手动创建sqlite数据库和表 con.row_factory = sqlite3.Row #将设置row_factory为callable sqlite3.Row,将普通元组转换为更有用的对象。 cur = con.cursor() cur.execute('select * from contact') rows = cur.fetchall() return render_template('show.html',rows = rows) if __name__ == "__main__": app.run('0.0.0.0',5000,debug=True) templates/home.html <html> <head> <meta charset="UTF-8"> <title>SQLITE3数据库的读写</title> </head> <h1>SQLITE3数据库的读写</h1> <p> <a href="/contact">点击进入联系人信息录入界面</a> </p> <br> <p> <a href="/show">点击进入联系人信息查看界面</a> </p> <body> </body> templates/contact.html <html> <head> <meta charset="UTF-8"/> <title>联系人表单填写</title> </head> <body> <h1>联系人表单填写 </h1> {% with msg = get_flashed_messages() %} {% if msg %} {% for i in msg %} {{ i }} {% endfor %} {% endif %} {% endwith %} {% for msg in form.name.errors %} <div>{{ msg }}</div> {% endfor %} {% for msg in form.email.errors %} <div>{{ msg }}</div> {% endfor %} {% for msg in form.age.errors %} <div>{{ msg }}</div> {% endfor %} <form action="/contact" method="post"> <fieldset> <legend>联系人表单填写内容</legend> <!-- 渲染所有隐藏字段,包括跨站请求伪造保护 --> {{ form.hidden_tag() }} <div style=" font-size:20px;font-weight:bold; margin-left: 600px;"> {{ form.name.label }} <br> {{ form.name }} <br> {{ form.gender.label }} {{ form.gender }} <br> {{ form.address.label }} <br> {{ form.address }} <br> {{ form.email.label }} <br> {{ form.email }} <br> {{ form.age.label }} <br> {{ form.age }} <br> {{ form.language.label }} <br> {{ form.language }} <br> {{ form.submit }} <br> <p> <a href="/">点击返回首页</a> </p> </div> </fieldset> </form> </body> </html> templates/show.html <html> <head> <meta charset="UTF-8"> <title>联系人信息查看界面</title> </head> <body> <h1>联系人信息查看界面</h1> <table border = 1> <thead> <td>Name</td> <td>gender</td> <td>gender</td> <td>age</td> <td>language</td> </thead> {% for i in rows %} <tr> <td>{{i["name"]}}</td> <td>{{i["gender"]}}</td> <td> {{ i["email"]}}</td> <td>{{i['age']}}</td> <td>{{i['language']}}</td> </tr> {% endfor %} </table> <p><a href="/">Go to home!!</a></p> </body> </html> templates/result.html <html> <head> <meta charset="UTF-8"> <title>SQLITE3数据库读写返回状态</title> </head> <h1>SQLITE3数据库读写返回状态</h1> {{ msg }} <br> <p><a href="/">Go to home!!</a></p> <body> </body> </html> Flask SQLAlchemy SQLAlchemy,Python工具包是一个强大的ORM,将内容存储在对象的方式模块安装SQLAlchemy 1.3版本Flask-SQLAlchemy 2.4.4版本 templates/home.html <html> <head> <meta charset="UTF-8"> <title>SQLAlchemy SQL工具包及对象关系映射(ORM)工具</title> </head> <body> <h1>SQLAlchemy SQL工具包及对象关系映射(ORM)工具</h1> <p> <a href="/newstu">点击进入学生信息录入界面</a> </p> <br> <p> <a href="/showstu">点击进入学生信息查看界面</a> </p> </body> </html> templates/newstu.html <html> <head> <meta charset="UTF-8"> <title>学生信息录入-Flask SQLAlchemy 使用</title> </head> <h1>学生信息录入-Flask SQLAlchemy 使用</h1> {% for msg in get_flashed_messages() %} {{ msg }} {% endfor %} <form action="{{ url_for('stu') }}" method="post"> <p>姓名:<input type="text" name="name"></p> <p>城市:<input type="text" name="city"></p> <p>地址:<textarea name="addr"></textarea></p> <p>手机号码:<input type="text" name="phone"></p> <p><input type="submit" value="submit"></p> </form> <a href="/">返回主页</a> </html> templates/showstu.html <html> <head> <meta charset="UTF-8"> <title>学生信息查询结果</title> </head> <h1>学生信息查询结果</h1> <table border = 1> <thead> <tr> <th>姓名</th> <th>城市</th> <th>地址</th> <th>手机号码</th> </tr> </thead> <tbody> {% for stu in students %} <tr> <td>{{stu.name}}</td> <td>{{stu.city}}</td> <td>{{stu.addr}}</td> <td>{{stu.phone}}</td> </tr> {% endfor %} </tbody> </table> <a href="/">返回主页</a> </html> Hello_development.py from flask import Flask,render_template,request,flash import os,pymysql from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.secret_key = os.urandom(32) # 设置连接sqlite3数据库的URL # app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///stu.db' # app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False # 设置连接mysql数据库的URL app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123456@192.168.5.157:3306/test' # 设置每次请求结束后会自动提交数据库的改动 app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True # 查询时显示原始SQL语句 #app.config['SQLALCHEMY_ECHO'] = True db = SQLAlchemy(app) ##实例化 class Students(db.Model): ##继承父类Model __tablename__ = 'students' id = db.Column('student_id', db.Integer, primary_key = True) name = db.Column(db.String(100)) city = db.Column(db.String(200)) addr = db.Column(db.String(100)) phone = db.Column(db.String(200)) def __init__(self, name, city, addr, phone): self.name = name self.city = city self.addr = addr self.phone = phone @app.route('/') def home(): #db.create_all() ##可以用这个来创建表结构一般创建完就注释的 return render_template('home.html') @app.route('/newstu') def newstu(): return render_template('newstu.html') @app.route('/showstu') def showstu(): return render_template('showstu.html',students = Students.query.all()) @app.route('/stu',methods=['POST']) def stu(): if request.method == 'POST': if not request.form['name'] or not request.form['city'] or not request.form['addr'] or not request.form['phone']: flash('Input cannot be empty') else: student = Students(request.form['name'],request.form['city'],request.form['addr'],request.form['phone']) db.session.add(student) db.session.commit() flash("Record was successfully added") return render_template('newstu.html') if __name__ == "__main__": app.run('0.0.0.0',5000,debug=True) Flask AJAX AJAX不是JavaScript的规范,它只是一个哥们“发明”的缩写:Asynchronous JavaScript and XML,意思就是用JavaScript执行异步网络请求。如果仔细观察一个Form的提交,你就会发现,一旦用户点击“Submit”按钮,表单开始提交,浏览器就会刷新页面,然后在新页面里告诉你操作是成功了还是失败了。如果不幸由于网络太慢或者其他原因,就会得到一个404页面。这就是Web的运作原理:一次HTTP请求对应一个页面。如果要让用户留在当前页面中,同时发出新的HTTP请求,就必须用JavaScript发送这个新请求,接收到数据后,再用JavaScript更新页面,这样一来,用户就感觉自己仍然停留在当前页面,但是数据却可以不断地更新。最早大规模使用AJAX的就是Gmail,Gmail的页面在首次加载后,剩下的所有数据都依赖于AJAX来更新。用JavaScript写一个完整的AJAX代码并不复杂,但是需要注意:AJAX请求是异步执行的,也就是说,要通过回调函数获得响应 templates/ajax.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>ajax</title> <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script> <body> <form id="my_form"> name: <input name="name" type="text"/><br> age: <input name="age" type="text"/><br> <input id="my_button" type="button" value="button"/> </form> <script> $("#my_button").click(function () { $.ajax({ url:"/test_post", type:"POST", dataType:"json", async:true, data:$("#my_form").serialize(), success:function (result) { // 回调函数,处理app.py返回的结果 alert(result['ok']) }, error:function (XMLHttpRequest,textStatus,errorThrown) { alert(XMLHttpRequest.status) alert(XMLHttpRequest.readyState) alert(textStatus) } }); }) </script> </body> </html> Hello_development.py import os,json from flask import Flask,render_template,jsonify,request,redirect,url_for app = Flask(__name__) @app.route('/') def home(): return render_template('ajax.html') @app.route('/test_post',methods=['POST','GET']) def test_post(): if request.method == 'POST': name=request.form.get('name') age=request.form.get('age') print(name,age) return jsonify({'ok': True}) return redirect(url_for('home')) if __name__ == "__main__": app.run('0.0.0.0',5000,debug=True) 以上全部代码均实操通过,时间20210322

优秀的个人博客,低调大师

2020年12月-前端基础-表格 table

表格 table(会使用) 为了让我们页面显示的更加整齐,我们需要学习三个表(表格、表单、列表) 理解: 能说出表格用来做什么的 表格的基本结构组成 表格作用: 存在即是合理的。 表格的现在还是较为常用的一种标签,但不是用来布局,常见显示、展示表格式数据。 因为它可以让数据显示的非常的规整,可读性非常好。 特别是后台展示数据的时候表格运用是否熟练就显得很重要, 一个清爽简约的表格能够把繁杂的数据表现得很有条理 ,虽然 div 布局也可以做到,但是总没有表格来得方便。 ps: 这些地方用表格,你会觉得很贴切。 1. 创建表格 在HTML网页中,要想创建表格,就需要使用表格相关的标签。 创建表格的基本语法: <table> <tr> <td>单元格内的文字</td> ... </tr> ... </table> 要深刻体会表格、行、单元格他们的构成。 在上面的语法中包含基本的三对HTML标签,分别为 table、tr、td,他们是创建表格的基本标签,缺一不可,下面对他们进行具体地解释 1.`table`用于定义一个表格标签。 2.`tr`标签 用于定义表格中的行,必须嵌套在`table`标签中。 3.`td` 用于定义表格中的单元格,必须嵌套在`<tr></tr>`标签中。 4.字母`td`指表格数据(table data),即数据单元格的内容,现在我们明白,表格最合适的地方就是用来存储数据的。 总结: 表格的主要目的是用来显示特殊数据的 一个完整的表格有表格标签(table),行标签(tr),单元格标签(td)组成,没有列的标签 <tr></tr>中只能嵌套<td></td> 类的单元格 <td></td>标签,他就像一个容器,可以容纳所有的元素 2. 表格属性 表格有部分属性我们不常用,这里重点记住 cellspacing 、 cellpadding。 我们经常有个说法,是三参为0, 平时开发的我们这三个参数 border cellpadding cellspacing 为 0 案例1: <table width="500" height="300" border="1" cellpadding="20" cellspacing="0" align="center"> <tr> <th>姓名</th> <th>性别</th> <th>年龄</th> </tr> <tr> <td>刘德华</td> <td>男</td> <td>55</td> </tr> <tr> <td>郭富城</td> <td>男</td> <td>52</td> </tr> <tr> <td>张学友</td> <td>男</td> <td>58</td> </tr> <tr> <td>黎明</td> <td>男</td> <td>18</td> </tr> <tr> <td>刘晓庆</td> <td>女</td> <td>63</td> </tr> </table> 3. 表头单元格标签th 作用: 一般表头单元格位于表格的第一行或第一列,并且文本加粗居中 语法: 只需用表头标签<th></th>替代相应的单元格标签<td></td>即可。 案例2: 效果图 代码: <table width="500" border="1" align="center" cellspacing="0" cellpadding="0"> <tr> <th>姓名</th> <th>性别</th> <th>电话</th> </tr> <tr> <td>小王</td> <td>女</td> <td>110</td> </tr> <tr> <td>小明</td> <td>男</td> <td>120</td> </tr> </table> th 也是一个单元格 只不过和普通的 td单元格不一样,它会让自己里面的文字居中且加粗 4. 表格标题caption 定义和用法 <table> <caption>我是表格标题</caption> </table> **注意: ** 1.`caption` 元素定义表格标题,通常这个标题会被居中且显示于表格之上。 2.`caption` 标签必须紧随 table 标签之后。 3.这个标签只存在表格里面才有意义。 5. 合并单元格(难点) 合并单元格是我们比较常用的一个操作,但是不会合并的很复杂。 5.1 合并单元格2种方式 跨行合并:rowspan="合并单元格的个数" 跨列合并:colspan="合并单元格的个数" 5.2 合并单元格顺序 合并的顺序我们按照 先上 后下 先左 后右 的顺序 5.3 合并单元格三步曲 1.先确定是跨行还是跨列合并 2.根据 先上 后下 先左 后右的原则找到目标单元格 然后写上 合并方式 还有 要合并的单元格数量 比如 : `<td colspan="3"> </td>` 3.删除多余的单元格 单元格 6. 总结表格 标签名 定义 说明 <table></table> 表格标签 就是一个四方的盒子 <tr></tr> 表格行标签 行标签要再table标签内部才有意义 <td></td> 单元格标签 单元格标签是个容器级元素,可以放任何东西 <th></th> 表头单元格标签 它还是一个单元格,但是里面的文字会居中且加粗 <caption></caption> 表格标题标签 表格的标题,跟着表格一起走,和表格居中对齐 clospan 和 rowspan 合并属性 用来合并单元格的 1.表格提供了HTML 中定义表格式数据的方法。 2.表格中由行中的单元格组成。 3.表格中没有列元素,列的个数取决于行的单元格个数。 4.表格不要纠结于外观,那是CSS 的作用。 5.表格的学习要求: 能手写表格结构,并且能简单合并单元格。 7. 拓展阅读@ 表格划分结构(了解) 对于比较复杂的表格,表格的结构也就相对的复杂了,所以又将表格分割成三个部分:题头、正文和脚注。而这三部分分别 用:thead,tbody,tfoot来标注, 这样更好的分清表格结构 注意: 1.`<thead></thead>:`用于定义表格的头部。用来放标题之类的东西。`<thead>` 内部必须拥有 `<tr>` 标签! 2.`<tbody></tbody>:`用于定义表格的主体。放数据本体 。 3.`<tfoot></tfoot>: `放表格的脚注之类。 4.以上标签都是放到table标签中。

优秀的个人博客,低调大师

图像处理基础:颜色空间及其OpenCV实现

点击上方“AI公园”,关注公众号,选择加“星标“或“置顶” 作者:Soumyadip Sarkar 编译:ronghuaiyang 导读 对图像的颜色空间做了一个概念性的介绍,并通过代码的方式可视化了每种颜色空间的每个通道所表示的意义。 文章内容包括: 什么是颜色空间? 颜色空间有哪些类别? 如何在OpenCV中实现? 什么是颜色空间? 颜色是一种连续的现象,它意味着有无数种颜色。但是,人类的眼睛和感知能力是有限的。所以,为了识别这些颜色,我们需要一种媒介或这些颜色的表示,这种颜色的表示被称为色彩空间。在技术术语中,一个颜色模型或颜色空间是一个特定的3-D坐标系统以及该系统中的一个子空间,其中每一种颜色都由一个单点表示。 有哪些颜色空间的类型? 目前主要有五种类型的颜色模型。但是,我将只写一些常见的(RGB、HSV和HSL)。 RGB(Red Green Blue) HSL(Hue Saturation Lightness) HSV(Hue Saturation Value) YUV(Luminance, blue–luminance, red–luminance) CMYK(Cyan, Magenta, Yellow, Key) RGB颜色空间: RGB颜色空间是三维坐标系中红、绿、蓝坐标所表示的著名颜色空间之一。在更专业的术语中,RGB将颜色描述为由三个部分组成的元组。每个部分都可以取0到255之间的值,其中元组(0,0,0)表示黑色,元组(255,255,255)表示白色。元组的第0、第1和第2个部分分别表示红、绿、蓝的分量。 RGB颜色空间的Python实现: 这里我们导入了必要的库,cv2用于颜色空间转换,NumPy用于数组操作,Matplotlib用于显示图像,os用于访问图像目录,tqdm用于显示加载栏。 hsl_img=cv2.cvtColor(X[0],cv2.COLOR_BGR2HLS)####CONVERTINGBGRCOLORSPACEINTOHSLCOLORSPACE####hsl_img_1=hsl_img.copy()hsl_img_2=hsl_img.copy()hsl_img_3=hsl_img.copy()hsl_img_1[:,:,1]=0####HUE-->ZERO####hsl_img_1[:,:,2]=0hsl_img_2[:,:,0]=0####SATURATION-->ZERO####hsl_img_2[:,:,2]=0hsl_img_3[:,:,0]=0####LIGHTNESS-->ZERO####hsl_img_3[:,:,1]=0 设置两个空列表Z和X,分别用于存储带有各自图像的标签,然后指定图像大小和路径目录。在这之后,我定义了两个函数,用于返回flower类型(assign_lable)和访问每个图像、读取和调整其大小(make_train_data)。 Z,X=[],[]IMG_SIZE=150FLOWER_SUNFLOWER_DIR='../input/flowers-recognition/flowers/flowers/sunflower'defassign_label(img,flower_type):returnflower_typedefmake_train_data(flower_type,DIR):forimgintqdm(os.listdir(DIR)):label=assign_label(img,flower_type)path=os.path.join(DIR,img)img=cv2.imread(path,cv2.IMREAD_COLOR)img=cv2.resize(img,(IMG_SIZE,IMG_SIZE))#Resizingtheimage 加载图像,然后在OpenCV以BGR格式读取图像时将BGR颜色空间转换为RGB颜色空间,但Maplotlib使用RGB格式来显示图像。这就是为什么我们需要转换颜色空间后,读取图像为RGB。 然后对固定图像进行三份拷贝,并将每份拷贝的任何双色通道设为零,分别用于访问红、绿、蓝通道。如果你让第0个颜色通道都是0那么你只会得到蓝色通道。 make_train_data('Sunflower',FLOWER_SUNFLOWER_DIR)#####LoadingSunflowerDatafix_img=cv2.cvtColor(X[0],cv2.COLOR_BGR2RGB)###########CONVERTINGBGRCOLORSPACEINTORGBCOLORSPACE#########new_img_1=fix_img.copy()new_img_2=fix_img.copy()new_img_3=fix_img.copy()new_img_1[:,:,0]=0#makingRchannelzero####ForBLUEchannel#####new_img_1[:,:,1]=0#makingGchannelzeronew_img_2[:,:,1]=0####ForREDcolorChannel####new_img_2[:,:,2]=0new_img_3[:,:,0]=0###ForGREENChannel####new_img_3[:,:,2]=0 显示图像: f,axes=plt.subplots(1,3,figsize=(15,15))list=[new_img_1,new_img_2,new_img_3]i=0foraxinaxes:ax.imshow(list[i])i+=1 HSL颜色空间: HSL的一般含义是色调、饱和度和明度。你可以将HSL以圆柱体的形式可视化,如图2(a)所示。围绕圆柱体的是不同的颜色,比如绿色、黄色、红色等等(我们真正想要的颜色)。饱和度是指颜色的多少,而明度是指颜色有多暗或多亮。正如你所看到的,圆柱体的顶部全是白色,底部全是黑色。 图2:HSL颜色空间 HSL颜色空间的Python实现: 使用OpenCV函数**cvtColor()**将BGR颜色空间转换为HSL颜色空间,在这里我们需要传递图像,以及从哪个颜色空间到哪个颜色空间我们想要改变图像。然后再复制并使两个颜色通道为零,以便分别显示每个颜色通道。 hsl_img=cv2.cvtColor(X[0],cv2.COLOR_BGR2HLS)####CONVERTINGBGRCOLORSPACEINTOHSLCOLORSPACE####hsl_img_1=hsl_img.copy()hsl_img_2=hsl_img.copy()hsl_img_3=hsl_img.copy()hsl_img_1[:,:,1]=0####HUE-->ZERO####hsl_img_1[:,:,2]=0hsl_img_2[:,:,0]=0####SATURATION-->ZERO####hsl_img_2[:,:,2]=0hsl_img_3[:,:,0]=0####LIGHTNESS-->ZERO####hsl_img_3[:,:,1]=0 现在显示三个不同的颜色通道→ f,axes=plt.subplots(1,3,figsize=(15,15))list=[hsl_img_1,hsl_img_2,hsl_img_3]i=0foraxinaxes:ax.imshow(list[i])i+=1 HSV颜色空间: HSV这个名字来自于颜色模型的三个坐标,即色相、饱和度和值。它也是一个圆柱形的颜色模型,圆柱体的半径表示饱和度,垂直轴表示值,角度表示色调。对于观察者,色调是占主导地位的,饱和度是混合到色调中的白光的数量,value是chrome的强度,value较低颜色变得更加类似于黑色,value越高,颜色变得更加像颜色本身。通过改变这些参数,我们可以生成不同的颜色。 图3:HSV颜色空间 HSV颜色空间的Python实现: 使用cvtColor()函数将色彩空间转换为HSV色彩空间。然后再复制并使两个通道置为零,以便分别显示每个通道。 hsv_img=cv2.cvtColor(X[0],cv2.COLOR_BGR2HSV)hsv_img_1=hsv_img.copy()hsv_img_2=hsv_img.copy()hsv_img_3=hsv_img.copy()hsv_img_1[:,:,1]=0#HUE-->ZEROhsv_img_1[:,:,2]=0hsv_img_2[:,:,0]=0#SATURATION-->ZEROhsv_img_2[:,:,2]=0hsv_img_3[:,:,0]=0#VALUE-->ZEROhsv_img_3[:,:,1]=0 单独显示每个颜色通道: —END— 英文原文:https://medium.com/analytics-vidhya/image-processing-series-part1-colorspaces-836d2e3ca700 请长按或扫描二维码关注本公众号 喜欢的话,请给我个在看吧! 本文分享自微信公众号 - AI公园(AI_Paradise)。如有侵权,请联系 support@oschina.cn 删除。本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

资源下载

更多资源
Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

WebStorm

WebStorm

WebStorm 是jetbrains公司旗下一款JavaScript 开发工具。目前已经被广大中国JS开发者誉为“Web前端开发神器”、“最强大的HTML5编辑器”、“最智能的JavaScript IDE”等。与IntelliJ IDEA同源,继承了IntelliJ IDEA强大的JS部分的功能。

用户登录
用户注册