标签: Python

  • 使用python3拆分大文件txt 图文教程

    使用python3拆分大文件txt 图文教程

    最近网站被攻击,cdn一下被打2TB,然后下载了日志进行分析,但是日志文件有几十兆,所以需要做一下切割,这里我们记一下python3的拆分文件脚本,以备后用。

    Python作为快速开发工具,其代码表达力强,开发效率高,因此用Python快速写一个,还是可行的。

    python3代码脚本

    import os
    import sys
    import random
    import threading
    import requests
    from urllib.parse import urlparse, urljoin
    from bs4 import BeautifulSoup
    import re
    import time
    lock = threading.Lock()
    class TotalSizeCounter:
        def __init__(self):
            self.total_size = 0
            self.lock = threading.Lock()
        def add_size(self, size):
            with self.lock:
                self.total_size += size
        def get_total_size(self):
            with self.lock:
                return self.total_size
    total_size_counter = TotalSizeCounter()
    # 生成随机的User-Agent头部信息
    def generate_user_agent():
        user_agents = [
            # iOS
            "Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/84.0.4147.122 Mobile/15E148 Safari/604.1",
            "Mozilla/5.0 (iPad; CPU OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/84.0.4147.122 Mobile/15E148 Safari/604.1",
            
            # Android
            "Mozilla/5.0 (Linux; Android 11; Pixel 5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.54 Mobile Safari/537.36",
            "Mozilla/5.0 (Linux; Android 11; SM-G998B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.54 Mobile Safari/537.36",
            
            # Windows
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.54 Safari/537.36",
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Edge/94.0.992.31",
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Firefox/100.0",
            # macOS
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 11_6_1) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Safari/605.1.15",
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 11_6_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.54 Safari/537.36",
            
            # Linux
            "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.54 Safari/537.36",
            "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:95.0) Gecko/20100101 Firefox/95.0"
        ]
        return random.choice(user_agents)
    def download_image(url, user_agent, output_folder):
        try:
            headers = {'User-Agent': user_agent}
            response = requests.get(url, headers=headers)
            response.raise_for_status()
            parsed_url = urlparse(url)
            filename = os.path.join(output_folder, os.path.basename(parsed_url.path))
            filename = f"{os.path.splitext(filename)[0]}_{random.randint(1, 10000)}{os.path.splitext(filename)[1]}"
            with lock:
                with open(filename, 'wb') as file:
                    file.write(response.content)
                    file_size = os.path.getsize(filename)
                    total_size_counter.add_size(file_size)
                    print(f"Downloaded image {url} as {filename}, Size: {file_size / (1024 * 1024):.2f} MB")
        except Exception as e:
            print(f"Error downloading image {url}: {e}")
    def download_images(url, user_agent, output_folder):
        try:
            headers = {'User-Agent': user_agent}
            response = requests.get(url, headers=headers)
            response.raise_for_status()
            soup = BeautifulSoup(response.content, 'html.parser')
            img_tags = soup.find_all('img')
            for img_tag in img_tags:
                img_url = img_tag.get('src')
                if img_url and not img_url.startswith(('data:', 'http:', 'https:')):
                    img_url = urljoin(url, img_url)
                    thread = threading.Thread(target=download_image, args=(img_url, user_agent, output_folder))
                    thread.start()
                    thread.join()
            img_urls_from_text = re.findall(r'<img[^>]*data-src=["\'](https?://[^"\']+\.(?:png|jpg|jpeg|gif|bmp))["\'][^>]*>', response.text)
            for img_url in img_urls_from_text:
                thread = threading.Thread(target=download_image, args=(img_url, user_agent, output_folder))
                thread.start()
                thread.join()
        except Exception as e:
            print(f"Error downloading images from {url}: {e}")
    def main(url, num_iterations):
        start_time = time.time()  # 记录开始时间
        if not os.path.exists("files"):
            os.makedirs("files")
        threads = []
        for _ in range(num_iterations):
            user_agent = generate_user_agent()
            thread = threading.Thread(target=download_images, args=(url, user_agent, "files/"))
            thread.start()
            threads.append(thread)
        for thread in threads:
            thread.join()
        end_time = time.time()  # 记录结束时间
        execution_time = end_time - start_time
        total_downloaded_size_mb = total_size_counter.get_total_size() / (1024 * 1024)
        print(f"Total downloaded size from all threads: {total_downloaded_size_mb:.2f} MB")
        print(f"Script execution time: {execution_time:.2f} seconds")
        # 删除"files"目录及其内容
        if os.path.exists("files"):
            for file_name in os.listdir("files"):
                file_path = os.path.join("files", file_name)
                os.remove(file_path)
            os.rmdir("files")
    if __name__ == "__main__":
        if len(sys.argv) != 3:
            print("Usage: python script.py <url> <num_iterations>")
        else:
            url = sys.argv[1]
            num_iterations = int(sys.argv[2])
            main(url, num_iterations)

    请在空目录汇总运行,脚本将自动当前目录创建files文件夹,脚本执行完成后删除所有下载的文件。

    脚本将会计算所有下载的大小以及执行花费时间。

  • python命令 – 解释器、交互式、面向对象的编程语言

    python命令 – 解释器、交互式、面向对象的编程语言

    Python是一种解释型的、交互式的、面向对象的编程语言,它结合了非凡的功能和非常清晰的语法。Python Library Reference记录了内置的和标准的类型、常量、函数和模块。

    语法格式:python [参数]

    常用参数:

    -c直接运行python语句
    -v会输出每一个模块引用信息
    -i运行完python脚本文件以后打开一个python环境
    -m将模块按照脚本执行

    参考实例

    直接运行python语句:

    [root@jiloc ~]# python -c "print 'Hello world'"

    查看python所有模块应用的信息:

    [root@jiloc ~]# python -v

    运行完python脚本文件以后打开一个python环境:

    [root@jiloc ~]# python -i main.py

    将模块按照脚本执行,实现一个简单的下载服务器:

    [root@jiloc ~]# python -m SimpleHTTPServer 80
  • 使用宝塔面板快速部署Django项目

    使用宝塔面板快速部署Django项目

    这是一个专门为新得不能再新的新手准备的教程,能快速让新手部署Django,让新手少走一些不必要的弯路,节省大量时间。之前发布了几篇文章,教大家如何在一些常见的操作系统下部署Django项目,得到了不少网友支持。部署Django项目我们一般都推荐使用Linux操作系统,这样能更加效率的运行Django。教程发布出来之后,有很多网友联系上了我,说是新手不会使用Linux操作系统,不熟悉Linux命令。奈何,最终还是我一个人扛下了所有,一一远程帮他们解决。

    刚开始的时候,人少还好说,后来加我的人越来越多,都是问一些基本的常识的问题。最终促使我写了这篇文章,这篇文章是基于Centos操作系统下使用宝塔面板来部署Django项目。全程只使用几个命令,让不管再怎么新的新手也能快速部署Django项目。言归正传,下面就教大家如何部署。

    场景:假设我们刚购买了一台新的Linux服务器,已经安装好Centos操作系统。

    1、在服务器供应商管理后台安全组里开放必要端口。

    国内的云服务器是把所有的端口给屏蔽了的,如果想使用的话需要自己在服务器提供商后台里的安全组里开放端口。比较常见的是阿里云、腾讯云、百度云等。大多数的服务器商是不需要做此操作的。我们需要开通的端口一般为:80、443、21、22、3306、8888,这些端口具体的用处我就不一一介绍了,但8888端口主要是用于访问宝塔的。

    2、下载Xshell软件。

    Xshell软件主要是用来登录Linux服务器的,使用方法很简单,自己百度下载就Ok。我们下载安装好之后,就登录服务器。

    3、系统根目录上创建WWW目录。

    终端输入命令:

    mkdir /www

    这个目录主要是用于存放宝塔面板和网站(项目)数据的。如果服务器有多个数据盘,建议把磁盘挂在到 /www目录下。

    4、安装宝塔面板

    我们直接终端输入下面的命令安装宝塔面板:

    yum install -y wget && wget -O install.sh http://download.bt.cn/install/install_6.0.sh && sh install.sh

    更多的信息可以访问下面的地址查看:https://www.bt.cn/bbs/thread-19376-1-1.html

    安装过程很简单,就不做过多介绍。这个时候我们可以泡点茶,喝点茶,做等就好。安装成功之后就看到如下类似的信息:

    20180413103653.jpg

    这个是宝塔面板的登录地址、用户名和登录密码,你需要把这个复制保存起来。

    更多关于宝塔的其它操作,可以直接在终端输入:bt,回车然后得到如下的选项:

    200606024440.jpg

    我们在浏览器里访问之前保存的那个地址,那个地址是用来登录宝塔面板,管理宝塔面板的。

    dfdfdfdf.jpg

    5、安装常用的WEB服务组件。

    登录成功岳我们可以看到如下界面:

    0200606005717.jpg

    这里面只有Nginx是必须要安装的,如果你使用的是Mysql数据库,那么Mysql也勾选上(留意Django3.0之后的版本不再支持Mysql5.5版本),其它的你可以根据自己的需求来决定是否安装。后面如果想安装其它的,也可以在软件管理里安装。留意:软件名后面的三角符号点击它可以选择软件的版本。新手建议默认即可。选择好之后,点击一键安装。然后继续喝茶做等。

    6、安装Python项目管理插件

    这个安装成功之后,我们在左边的‘软件商店’里选择‘宝塔插件’,找到‘Python项目管理’这个插件进行安装。

    5.png
    6.png

    7、安装项目所需要的Python版本。

    安装成功之后,我们点击设置。

    8.png

    然后出现如下界面:

    9.png

    我们在版本管理里安装我们需要的Python版本。这里我以3.7.2为例,选择了国内的节点,国内节点安装会快一些。等一会就会安装成功。

    8、添加项目站点

    0200606011528.jpg

    域名处填写自己的域名即可,没有域名填写服务器IP地址。

    9、上传Django项目源码。

    留意:在打包项目源码之前,先在本地环境使用下面的命令把环境依赖包导出到requirements.txt文件里,并把这个文件存放在项目目录下,这一步奏非常重要,请务必记得操作。

    导出命令:

    pip freeze > requirements.txt

    这一步操作好之后,我们就通过下面的步骤把项目源码上传上到服务器上去。

    解压项目

    解压成功之后,就像下面那样。留意路径,记得源码一定要解压到根目录里。然后再检查一下,项目里有没有requirements.txt这个文件。

    10、添加uwsgi配置文件uwsgi.ini

    留意:新建一个空白文件,文件名为uwsgi.ini。新建成功之后输入如下代码,然后保存:

    #添加配置选择
    [uwsgi]
    #配置和nginx连接的socket连接
    socket=127.0.0.1:8997
    #配置项目路径,项目的所在目录
    chdir=/www/wwwroot/www.django.cn/
    #配置wsgi接口模块文件路径,也就是wsgi.py这个文件所在的目录
    wsgi-file=myblog/wsgi.py
    #配置启动的进程数
    processes=4
    #配置每个进程的线程数
    threads=2
    #配置启动管理主进程
    master=True
    #配置存放主进程的进程号文件
    pidfile=uwsgi.pid
    #配置dump日志记录
    daemonize=uwsgi.log`

    这里面,我们最需要留意的是项目路径和wsgi.py所在的目录。

    11、修改网站配置

    左侧网站,然后点击网站名,在弹出的窗口里找到’配置文件’,然后配置文件里输入如下代码:

        location / {
           include uwsgi_params;
           uwsgi_pass 127.0.0.1:8997;  #端口要和uwsgi里配置的一样
           uwsgi_param UWSGI_SCRIPT myblog.wsgi;  #wsgi.py所在的目录名+.wsgi
           uwsgi_param UWSGI_CHDIR /www/wwwroot/www.django.cn/; #项目路径
        }
          location /static/ {
          alias /www/wwwroot/www.django.cn/static/; #静态资源路径
          }

    里面的端口、路径都要和uwsgi.ini里的一致。

    20200606020353.jpg

    12、Python项目管理插件里添加项目

    在左右的软件商店里找到Python项目管理插件,然后点击设置,添加项目。里面的各种选项很简单,按实际情况填写就行。

    值得说的就是那个端口,端口要和uwsgi.ini里面的那个端口一致。如果有多个项目的话,不同的项目要填写不同的端口。端口随便填写,只要不与其它常用软件端口冲突就好。

    留意:

    使用Python项目管理插件新建项目成功之后,会自动在项目j源码目录里创建一个虚拟环境,虚拟环境目录一般都是以项目名_venv形式命名的。

    进入虚拟环境方法:

    在命令行输入  source 项目路径/项目名_venv/bin/activate 如:

    source /www/wwwroot/myblog/myblog_venv/bin/activate

    项目管理器默认使用pip安装项目根目录requirements.txt内的模块,这也是之前我强调把环境依赖包文件放到项目目录下的原因,如有其他模块需要安装请手动进入虚拟环境安装。

    以上配置完成之后,基本已经部署完毕。我们在浏览器里访问我们的域名,就能查看到网站。

    14、解决管理后台样式丢失

    如果后台样式丢失了,如图:

    41711.jpg

    解决办法:

    在宝塔面板里,点击网站路径进入项目路径下,找到settins.py文件,我们在末尾处添加静态资源收集路径

    #把APP静态资源收集到指定的目录下,这里我收集到static目录下
    STATIC_ROOT  = os.path.join(BASE_DIR, 'static')
    0200606144546.jpg

    之后在SSH终端进入项目虚拟环境:

    source /www/wwwroot/myblog/myblog_venv/bin/activate

    成功进入虚拟环境会出现如下标记:

    0200606143449.jpg

    出现项目名_venv这个标记,才说明已经成功进入虚拟环境。

    然后我们使用下面的命令收集静态文件:

    python manage.py collectstatic

    如下图:

    20200606144101.jpg

    收集成功之后,刷新后台页面,样式就恢复正常。

    至此教程结束。

    问题整理:

    1、访问显示出现 Internal Server Error 之类的错误的话,可能是程序不能正常运行的原因。请进入虚拟环境下,使用python manage.py runserver 命令运行项目,看项目能不能正常运行,不能正常运行就按错误提示进行解决就好。程序能正常运行使用项目管理器重启一下项目就能正常访问。

    2、如果出现:Django运行提示:SQLite 3.8.3 or later is required (found 3.7.17)  这样的错误,请按这篇文章操作。https://www.jiloc.com/47542.html

    3、如果在第十二步建立项目时提现出错,请把“是否安装模块依赖”这个选项去掉,等项目建立完成之后再进入虚拟环境手动安装依赖模块。

  • Django Python 后台 列表中 自定义权限 筛选 根据用户权限自动筛选列表

    Django Python 后台 列表中 自定义权限 筛选 根据用户权限自动筛选列表

    在Django的项目开发中,需求是要在后台得列表中非管理员用户只列出自己的相关记录。下面我们记录一下 admin.py 详细的代码并给出详解。

    class Sale_Admin(admin.ModelAdmin):
        list_display = ('customer','idc', 'line_type', 'charge_type',  'saler', 'graph_id', 'alarm_times')
        list_per_page = 20
        # list_editable = ['graph_id',]
        list_filter = ('customer', 'saler')
        search_fields = ['customer__name','idc__name','graph_id']
        ordering = ('idc',)
        readonly_fields = ('v_max', 'v_nf', 'update_time', 'alarm_times')
        def get_queryset(self, request):
            qs = super(Sale_Admin,self).get_queryset(request)
            # if request.user.is_superuser:
            #     return qs
            return qs.filter(saler=23)
        def has_add_permission(self, request):
            return False
        def has_change_permission(self, request, obj=None):
            return False
        def has_delete_permission(self, request, obj=None):
            return False
        def has_view_permission(self, request, obj=None):
            return False

    get_queryset 可以自定义对象列表,比如非管理员登录,我们只显示saler值为23的记录。

    当然还可以控制当前用是否能查看、修改、添加、删除权限。

    has_add_permission has_change_permission has_delete_permission has_view_permission 则是判断是否具有对应的权限。

    Django 官方文档:https://docs.djangoproject.com/en/3.1/ref/class-based-views/mixins-single-object/#django.views.generic.detail.SingleObjectMixin.get_queryset

  • windows pip使用国内源 图文教程

    windows pip使用国内源 图文教程

    前面我们记录了MacOS 下 Python3 pip 配置国内源,下面我们记录一下Windows下更新pip源的方法。

    win+R 打开用户目录%HOMEPATH%,在此目录下创建 pip 文件夹,在 pip 目录下创建 pip.ini 文件, 内容如下

    在pip文件夹里新建的pip.ini代码如下

    [global]
    timeout = 6000
    index-url = https://pypi.tuna.tsinghua.edu.cn/simple
    trusted-host = pypi.tuna.tsinghua.edu.cn
  • MacOS 下 Python3 pip 配置国内源

    MacOS 下 Python3 pip 配置国内源

    国内源列表(推荐用阿里云的)

    阿里云http://mirrors.aliyun.com/pypi/simple/
     豆瓣 (douban)http://pypi.douban.com/simple/
    中国科技大学https://pypi.mirrors.ustc.edu.cn/simple/
    清华大学https://pypi.tuna.tsinghua.edu.cn/simple/
    中国科学技术大学http://pypi.mirrors.ustc.edu.cn/simple/

    方法一:安装时指定

    pip install ipython -i http://mirrors.aliyun.com/pypi/simple/

    如果提示 host 不被信任可以加上参数 –trusted-host

    pip install ipython -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com
    

    方法二:永久设置

    mkdir ~/.pip
    vi ~/.pip/pip.conf # 创建一个pip配置文件# 写入配置

    写入如下代码:

    [global]
    index-url = http://mirrors.aliyun.com/pypi/simple/
    [install]
    trusted-host = mirrors.aliyun.com
  • VPS库存监控系统

    VPS库存监控系统

    最近闲来无事,弄了一个基于的django+vue的东西出来,主要是用于监控一些商家的VPS库存情况。我们是vue新手,边学边做,有不对的地方还望大佬指点~

    安装/Install

    本环境需要python3的运行环境以及python3-pip下载源码后运行 ` pip3 install django `

    然后将数据库导入

    python3 manage.py makemigrations --merge ; python3 manage.py migrate

    创建后台超级用户

     python3 manage.py createsuperuser

    开始启动服务

    python3 manage.py runserver 0.0.0.0:80

    启动后,可以在浏览器中打开 http://127.0.0.1/admin 的“商品”及“商家”中填入数据,否则首页会运行报错。

    定时监控/Crontab

    定时每分钟检查VPS商家库存情况,需要在商家的属性中设定`检查库存`:`是`然后将以下命令加入到crontab中。(Linux命令详解:crontab 定时任务)

     */1 * * * * cd /data/wwwroot/vps-stock-monitor/ ; python3 manage.py run > /dev/null 2>&1 &

    如在windows系统中,需要加入到计划任务中。

  • Vue 实现分页效果 代码实例

    Vue 实现分页效果 代码实例

    分页思路:

    首先是定义页号currentPage 和 页大小pagesize,用一个数组保存总数据;

    用一个计算属性page_arrs,作用是 让页面展示的是我们所需要的页面

    而我们在page_arrs中要分割原数组,用一个slice()方法进行分割;

    在控件button上绑定点击方法,对页号currentPage进行修改,从而修改整个页面展示

    Python Django vue {{}} 括号冲突 问题 解决 图文教程

    分页css采用了bootstrap的标准代码,在使用时直接引用bootstrap的css即可。

    Javascript代码:

    var app = new Vue({
        delimiters:['{[', ']}'],//区分django的模板标记
        el: '#app',
        data: {
            arrs: {{goods|safe}},//django模板中原样输出
            titles : ['序号','服务商','机房',"CPU",'内存','硬盘','带宽','流量','线路','IPV4','架构','价格','库存'],
            currentPage : 1,//当前页号
            pagesize :12, //每页大小
            all:0,//总页数
        },  
        filters:{
            formatPrice: function(obj){
                $str = '';
                if(obj.annual)
                    $str += '$'+obj.annual+'/年<br/>';
                if(obj.quarter)
                    $str += '$'+obj.quarter+'/季<br/>';
                if(obj.month)
                    $str += '$'+obj.month+'/月<br/>';
                return $str;
            },
            stockToBuy: function(obj){
                if( obj.stock === 1 ){
                    return '<a href="//www.jiloc.com/go/bwh-'+obj.pid+'" class="btn btn-primary active" role="button" aria-pressed="true">购买</a>';
                }else{
                    return '<button class="btn btn-secondary" disabled="true">售罄</button>';
                }
            }
        },
        created: function () {
            var self = this;
            // $.ajax({
            //     // url: 'https://vpsdalao.com/api/records?provider=Bandwagon',
            //     url: '/ajax_goods',
            //     type: 'get',
            //     data: {},
            //     dataType: 'json'
            // }).then(function (res) {
            //     // console.log(res.data)
            //     self.items = res.data
            // }).fail(function () {
            //     console.log('失败');
            // })
        },
        computed:{
            page_arrs(){
                let {currentPage,pagesize,all} = this
                this.all = Math.ceil(this.arrs.length/pagesize)
                return this.arrs.slice((currentPage-1)*pagesize,currentPage*pagesize)
            },
            indexs: function(){
                var left = 1;
                var right = this.all;
                var ar = [];
                if(this.all>= 5){
                    if(this.currentPage > 3 && this.currentPage < this.all-2){
                        left = this.currentPage - 2
                        right = this.currentPage + 2
                    }else{
                        if(this.currentPage<=3){
                            left = 1
                            right = 5
                        }else{
                            right = this.all
                            left = this.all -4
                        }
                    }
                }
                while (left <= right){
                    ar.push(left)
                    left ++
                }
                return ar
            },
            current_page(){
                return this.currentPage
            }
        },
        methods: {
            primaryPage(){
                this.currentPage = 1
            },
            prePage(){
                if(this.currentPage == 1){
                    return
                }
                this.currentPage = this.currentPage - 1
            },
            nextPage(){
                if(this.currentPage == Math.ceil(this.arrs.length/this.pagesize)){
                    return
                }
                this.currentPage = this.currentPage + 1
            },
            lastPage(){
                this.currentPage = Math.ceil(this.arrs.length/this.pagesize)
            },
            btnClick: function(data){//页码点击事件
                if(data != this.currentPage){
                    this.currentPage = data 
                }
            },
        },
    })

    HTML代码部分

        <div class="container-fluid" id="app">
            <section class="text-center">
                <h1>VPS库存监控列表</h1>
                <p><a href="//www.jiloc.com/go/bwh">搬瓦工</a>优惠码:<code>BWH3HYATVBJW</code> ,
                <p>数据最后更新时间:<code>{{update_time}}</code></p>
            </section>
            <table class="table table-striped table-bordered table-hover">
                <thead>
                <tr>
                    <th v-for="title in titles">{[title]}</th>
                </tr>
                </thead>
                <tbody>
                <tr v-for="(item,index) in page_arrs" :key="index">
                    <td>{[index+1]}#</td>
                    <td>{[item.company__name]}</td>
                    <td>{[item.dc]}</td>
                    <td>{[item.cpu]}</td>
                    <td>{[item.ram]}</td>
                    <td>{[item.disk]}</td>
                    <td>{[item.bandwidth]}</td>
                    <td>{[item.traffic]}</td>
                    <td>{[item.route]}</td>
                    <td>{[item.ipv4]}</td>
                    <td>{[item.arch]}</td>
                    <td v-html="$options.filters.formatPrice(item)"></td>
                    <td v-html="$options.filters.stockToBuy(item)" ></td>
                </tr>
                </tbody>
            </table>
            <nav aria-label="Page navigation">
                <ul class="pagination  justify-content-center">
                  <li :class="current_page == 1 ? 'page-item disabled' : 'page-item' "><a class="page-link" href="#" @click="primaryPage"> << </a></li>
                  <li :class="current_page == 1 ? 'page-item disabled' : 'page-item' "><a class="page-link" href="#" @click="prePage"> < </a></li>
                  <li v-for="index in indexs" :class="current_page == index ? 'page-item active' : 'page-item' "><a class="page-link" href="#"  @click="btnClick(index)">{[ index ]}</a></li>
                  <li class="page-item disabled"><a class="page-link" href="#" aria-disabled="true">{[current_page]} / {[all]}</a></li>
                  <li :class="current_page == all ? 'page-item disabled' : 'page-item' "><a class="page-link" href="#" @click="nextPage()"> > </a></li>
                  <li :class="current_page == all ? 'page-item disabled' : 'page-item' "><a class="page-link" href="#" @click="lastPage"> >> </a></li>
                </ul>
            </nav>
        </div>
  • python中的线程之semaphore控制每次信号量

    python中的线程之semaphore控制每次信号量

    semaphore是一个内置的计数器

    每当调用acquire()时,内置计数器-1
    每当调用release()时,内置计数器+1

    计数器不能小于0,当计数器为0时,acquire()将阻塞线程直到其他线程调用release()
    来看下面的代码:

    import time
    import threading
    def foo():
    	time.sleep(2)	#程序休息2秒
    	print("ok",time.ctime())
    for i in range(20):
    	t1=threading.Thread(target=foo,args=())	#实例化一个线程
    	t1.start()	#启动线程
    

    执行结果:

    ok Tue Jul 18 20:05:58 2017
    ok Tue Jul 18 20:05:58 2017
    ok Tue Jul 18 20:05:58 2017
    ok Tue Jul 18 20:05:58 2017
    ok Tue Jul 18 20:05:58 2017
    ok Tue Jul 18 20:05:58 2017
    ok Tue Jul 18 20:05:58 2017
    ok Tue Jul 18 20:05:58 2017
    ok Tue Jul 18 20:05:58 2017
    ok Tue Jul 18 20:05:58 2017
    ok Tue Jul 18 20:05:58 2017
    ok Tue Jul 18 20:05:58 2017
    ok Tue Jul 18 20:05:58 2017
    ok Tue Jul 18 20:05:58 2017
    ok Tue Jul 18 20:05:58 2017
    ok Tue Jul 18 20:05:58 2017
    ok Tue Jul 18 20:05:58 2017
    ok Tue Jul 18 20:05:58 2017
    ok Tue Jul 18 20:05:58 2017
    ok Tue Jul 18 20:05:58 2017

    可以看到,程序会在很短的时间内生成20个线程来打印一句话。

    如果在主机执行IO密集型任务的时候再执行这种类型的程序时,计算机就有很大可能会宕机。
    这时候就可以为这段程序添加一个计数器功能,来限制一个时间点内的线程数量。

    代码如下:

    import time
    import threading
    s1=threading.Semaphore(5)	#添加一个计数器
    def foo():
    	s1.acquire()	#计数器获得锁
    	time.sleep(2)	#程序休眠2秒
    	print("ok",time.ctime())
    	s1.release()	#计数器释放锁
    
    for i in range(20):
    	t1=threading.Thread(target=foo,args=())	#创建线程
    	t1.start()	#启动线程	
    

    执行结果:

    ok Tue Jul 18 20:04:38 2017
    ok Tue Jul 18 20:04:38 2017
    ok Tue Jul 18 20:04:38 2017
    ok Tue Jul 18 20:04:38 2017
    ok Tue Jul 18 20:04:38 2017
    ok Tue Jul 18 20:04:40 2017
    ok Tue Jul 18 20:04:40 2017
    ok Tue Jul 18 20:04:40 2017
    ok Tue Jul 18 20:04:40 2017
    ok Tue Jul 18 20:04:40 2017
    ok Tue Jul 18 20:04:42 2017
    ok Tue Jul 18 20:04:42 2017
    ok Tue Jul 18 20:04:42 2017
    ok Tue Jul 18 20:04:42 2017
    ok Tue Jul 18 20:04:42 2017
    ok Tue Jul 18 20:04:44 2017
    ok Tue Jul 18 20:04:44 2017
    ok Tue Jul 18 20:04:44 2017
    ok Tue Jul 18 20:04:44 2017
    ok Tue Jul 18 20:04:44 2017

  • rrdtool 生成 .xml .png 出现 rrdtool.OperationalError: the RRD does not contain an RRA matching the chosen CF

    rrdtool 生成 .xml .png 出现 rrdtool.OperationalError: the RRD does not contain an RRA matching the chosen CF

    公司业务需要,我们要将.rrd文件转化成.xml,修改内容再通过.xml转化成.rrd或者图形。在Ubuntu中转化正常,但是到了Centos下就报错如下:

    rrdtool.OperationalError: the RRD does not contain an RRA matching the chosen CF

    Ubuntu的rrdtool版本为:1.7.0

    Centos的rrdtool版本为:1.4.8

    可能是因为版本问题,然后我们写的.xml文件又不规范。python生成.xml的部分代码如下:

    tmp_xml_str += '<!-- {} UTC / {} --> <row><v>{}</v><v>{}</v></row>\n        '.format(write_time,tmp_time,traffic_in,traffic_out)
    xml_str = '\
    <?xml version="1.0" encoding="utf-8"?>\n\
    <!DOCTYPE rrd SYSTEM "http://oss.oetiker.ch/rrdtool/rrdtool.dtd">\n\
    <!-- Round Robin Database Dump -->\n\
    <rrd>\n\
        <version>0003</version>\n\
        <step>300</step> <!-- Seconds -->\n\
        <lastupdate>{}</lastupdate> <!-- {} UTC -->\n\
        <ds><name> traffic_in </name><type> COUNTER </type></ds>\n\
        <ds><name> traffic_out </name><type> COUNTER </type></ds>\n\
        <rra>\n\
            <cf>MAX</cf>\n\
            <pdp_per_row>1</pdp_per_row> <!-- 300 seconds -->\n\
            <database>\n\
                {} \
            </database>\n\
        </rra>\n\
    </rrd>'.format(tmp_time,write_time,tmp_xml_str)   

    注意:我们此处写的是 <cf>MAX</cf> 。原先我们这里写的是 <cf>AVERAGE</cf> ,但是我们在新的rrd生成图的时候写的又是MAX,可能这里2个参数不一致导致了以上错误。

  • Python Django vue {{}} 括号冲突 问题 解决 图文教程

    Python Django vue {{}} 括号冲突 问题 解决 图文教程

    我们在使用django+vue开发的时候,可能会遇到{{}}这种冲突的问题,因为这2个工具都是使用 {{}} 来包裹变量的。下面我们记录一下修改vue的默认包裹方法:

    全局修改

    Vue.config.delimiters = ["{[", "]}"]

    使用时部分修改

    new Vue({
      delimiters:['{[', ']}'],
      el: '.el',
      data:{}
     })
  • python requirements.txt 环境安装生成依赖列表及使用教程

    python requirements.txt 环境安装生成依赖列表及使用教程

    当我们在迁移python及django程序时,需要安装很多的依赖环境,下面我们记录一下安装依赖的方法,本人python新手。如有不对的地方,请指出。

    虚拟环境下生成

    pip freeze >requirements.txt

    生成后文件requirements.txt是这个样子:

    certifi==2018.1.18
    chardet==3.0.4
    idna==2.6
    pyaml==17.12.1
    PyYAML==3.12
    requests==2.18.4
    urllib3==1.22

    虚拟环境安装

    pip install -r requirements.txt
WeChat