压侧工具 ngrinder 学习(发送POST JSON请求)

[python] # -*- coding:utf-8 -*- # A simple example using the HTTP plugin that shows the retrieval of a # single page via HTTP. # # This script is automatically generated by ngrinder. # # @author admin from net.grinder.script.Grinder import grinder from net.grinder.script import Test from net.grinder.plugin.http import HTTPRequest from net.grinder.plugin.http import HTTPPluginControl from HTTPClient import NVPair #导入对JSON格式返回值的处理函数 from org.json import JSONObject import sys reload(sys) sys.setdefaultencoding('utf-8') control = HTTPPluginControl.getConnectionDefaults() # if you don't want that HTTPRequest follows the redirection, please modify the following option 0. # control.followRedirects = 1 # if you want to increase the timeout, please modify the following option. control.timeout = 6000 test1 = Test(1, "api.vd.cn") request1 = HTTPRequest() # Make any method call on request1 increase TPS test1.record(request1) class TestRunner: # initlialize a thread def __init__(self): grinder.statistics.delayReports=True pass # test method def __call__(self): headers = [ NVPair("Content-Type","application/json") ] json_data='{"is_card_photo":"1","wid":"200168668","BaseAppType":"android","BaseAppVersion":"4.4.0","SystemVersion":"4.4.2","shop_id":"11433415","_sign_":"DDFDDA37A35F2CF28591FC6D18245779","_token_":"53c571f37a7e2fe64cc4d24200fdd8ca","_wid_":"200168668","appIdentifier":"com.hs.yjseller"}' #submitdata = [NVPair("a","1"),NVPair("b","2"),NVPair("c","3")] result = request1.POST("http://your ip/user/getuseraddressall", json_data, headers) # You get the message body using the getText() method. # if result.getText().find("HELLO WORLD") != -1 : # grinder.statistics.forLastTest.success = 1 # else : # grinder.statistics.forLastTest.success = 0 # if you want to print out log.. Don't use print keyword. Instead, use following. #grinder.logger.info(result.getText()) if result.getStatusCode() == 200 : grinder.statistics.forLastTest.success = 1 elif result.getStatusCode() in (301, 302) : grinder.logger.warn("Warning. The response may not be correct. The response code was %d." % result.getStatusCode()) grinder.statistics.forLastTest.success = 1 else : grinder.statistics.forLastTest.success = 1 [/python]

压侧工具 ngrinder 学习(安装)

系统环境mac 自带的java版本1.8 对java tomcat 不是很熟悉 所以直接下载 ngrinder-controller-3.2.3-with-tomcat.tar.gz ngrinder-core-3.2.3-agent-package.tar.gz 2个压缩包 直接解压 并将bin目录添加到系统环境变量 启动 startup.sh 启动代理 run_agent.sh 编辑 ~/.ngrinder_agent/agent.conf start.mode=agent agent.console.ip=please specify your controller IP #monitor.listen.port=3243 #monitor.collector.interval=1 #monitor.controller.cache.size=128 #monitor.collector.interval=1 #start.mode=agent #agent.console.port=7001 #agent.region= 重新启动代理服务 这里发现个问题 测试时无法发现代理机 导致代理为0 解决方法 在代理管理中 把代理设置为启动即可

MAC matplotlib 错误 RuntimeError: Python is not installed as a framework.

在mac上装一个tensorflow做一些小的实验还是蛮方便的。用virtualenv的方式避免了很多麻烦。 sudo pip install --upgrade virtualenv virtualenv --system-site-packages tensorflow pip install --upgrade https://storage.googleapis.com/tensorflow/mac/tensorflow-0.7.1-py2-none-any.whl 但是在运行的时候发现报错:
from matplotlib.backends import _macosx RuntimeError: Python is not installed as a framework. The Mac OS X backend will not be able to function correctly if Python is not installed as a framework. See the Python documentation for more information on installing Python as a framework on Mac OS X. Please either reinstall Python as a framework, or try one of the other backends. If you are Working with Matplotlib in a virtual enviroment see ‘Working with Matplotlib in Virtual environments’ in the Matplotlib FAQ
解决的方法也很简单: vim ~/.matplotlib/matplotlibrc 然后输入以下内容: backend: TkAgg 转自 http://blog.csdn.net/patrick75/article/details/50885025

django admin 后台添加 富文本编辑器 kindeditor

python admin 后台添加 富文本编辑器 kindeditor 下载http://kindeditor.net/down.php  解压放到static目录下 添加config.js [javascript] KindEditor.ready(function(K) { function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); window.editor = K.create('#id_content',{ // 指定大小 width:'600px', minWidth:'600px', height:'400px', resizeType : 1, allowPreviewEmoticons : false, allowImageUpload : true, uploadJson: "/admin/upload", filePostName : 'file', extraFileUploadParams: {csrfmiddlewaretoken:csrftoken}, items:[ 'source', '|', 'undo', 'redo', '|', 'preview', 'print', 'code', 'cut', 'copy', 'paste', 'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright', 'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'clearhtml', 'quickformat', 'selectall', '/', 'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image', 'multiimage', 'insertfile', 'table', 'hr', 'emoticons', 'pagebreak', 'anchor', 'link', 'unlink' ] }); }); [/javascript] 编辑setting.py 添加 [python] STATIC_URL = '/static/' STATICFILES_DIRS = ( <em id="__mceDel">os.path.join(BASE_DIR, 'static'), )</em> MEDIA_URL = "http://127.0.0.1:8000/" MEDIA_ROOT = 'static/media/' [/python] 打开admin.py 在对应的class model中添加 加在js文件(注意根据自己的目录) [python] class Media: js = ( 'editor/kindeditor-all-min.js', 'editor/lang/zh_CN.js', 'editor/config.js', ) [/python] 在form model 中添加对应的form  注意textarea的id属性 要对应config.js 设置的属性 [python] class WpPostsForms(forms.ModelForm): post_title = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}), max_length=50,label=u'标题',required=True) post_content = forms.CharField(widget=forms.Textarea(attrs={'class':'form-control','id':'id_content'}), label=u'内容',required=True) class Meta: model = WpPosts fields=['post_title', 'post_content'] [/python] 打开页面 django1 处理编辑器上传图片 在view.py中添加一个action [python] from django.http import HttpResponse,HttpResponseRedirect from PIL import Image from django import forms import ImageFile from mysite import settings import time,os,json from django.core.urlresolvers import reverse def upload(request): if not request.user.is_authenticated(): return HttpResponseRedirect(reverse('admin:index', args=())) if request.method == "POST": msg = {} f = request.FILES["file"] ext = ['gif', 'jpg', 'jpeg', 'png', 'bmp'] if f.name.split('.')[-1] not in ext: msg["error"] = 1 msg["url"] = "" msg["message"] = "上传文件格式不正确" return HttpResponse(json.dumps(msg)) parser = ImageFile.Parser() for chunk in f.chunks(): parser.feed(chunk) img = parser.close() path = settings.MEDIA_ROOT + str(time.strftime("%Y%m%d", time.localtime(time.time()))) if os.path.exists(path) == False: os.mkdir(path) name = '%s%s' % (path + "/", f.name) img.save(name) msg["error"] = 0 msg["url"] = settings.MEDIA_URL + name return HttpResponse(json.dumps(msg)) [/python] 现在可以上传图片了 django2

ss服务搭建 翻墙

ss服务 代理  翻墙 服务器ubuntu14.04 lts apt-get install python-pip apt-get install python-m2crypto pip install shadowsocks mkdir /etc/shadowsocks vim /etc/shadowsocks/config.json apt-get install vim vim /etc/shadowsocks/config.json { "server":"服务器ip", "server_port":服务器端口, "local_port":本地端口, "password":"密码", "timeout":600, "method":"aes-256-cfb" } 启动 ssserver -c /etc/shadowsocks/config.json start 下载客户端 https://github.com/shadowsocks/shadowsocks/wiki/Ports-and-Clients#os-x 开启 qweqczcz C9GMKE[O$]@~QG8MCXR]651 MEZLP~QL$K`G~RC}B}EJ34B

pymongo 聚合查询group

获取重复的手机号 db.weikephone.insert({"wid":100000185, "phone": 13818070900}) db.weikephone.insert({"wid":100000186, "phone": 13818070900}) db.weikephone.insert({"wid":100000187, "phone": 13818070901}) db.weikephone.insert({"wid":100000188, "phone": 13818070902}) [python] import pymongo mondb = pymongo.MongoClient('localhost',27017) mondb = mondb["test"] pipline = [ {"$group" : {"_id" : "$phone", "count" : {"$sum" : 1}}}, {"$match" : {"count" : {"$gt" : 1}}} ] print list(mondb.weikephone.aggregate(pipline)) [/python] 等同于 select phone,count(*) as count from t_wm_weikephone group by phone having count>1

linux下压力测试软件siege的安装与使用详解

假定: 1 centos 系统 root登录 2 siege-2.72版本 下载自:http://www.joedog.org 3 openssl 安装路径 /usr/local/ssl 4 使用人员:php开发人员 关于siege的说明请先参考http://www.joedog.org 选择siege的理由: 1 稳定 2 除了对http支持外,还支持https,并且支持的很好,apachebanch 对https支持的不够好。 3 安装简单,功能够开发测试用 一、siege的安装 cd /root/ rz tar -zxvf siege-2.72.tar.gz cd siege-2.72 ./configure --prefix=/usr/local/siege --mandir=/usr/local/man --with-ssl=/usr/local/ssl mkdir -p /usr/local/siege/etc/ mkdir -p /usr/local/siege/var/ make make install 创建.siegec.config配置文件到当前用户的家目录下 /usr/local/siege/bin/siege.config 安装完成 查看配置文件 /usr/local/siege/bin/siege -C CURRENT SIEGE CONFIGURATION JoeDog/1.00 [en] (X11; I; Siege 2.72) Edit the resource file to change the settings. ---------------------------------------------- version: 2.72 verbose: false debug: false protocol: HTTP/1.1 connection: close concurrent users: 15 time to run: n/a repetitions: n/a socket timeout: 30 delay: 1 sec internet simulation: false benchmark mode: false failures until abort: 1024 named URL: none URLs file: /usr/local/siege/etc/urls.txt logging: true log file: /usr/local/siege/var/siege.log resource file: /root/.siegerc timestamped output: false comma separated output: false allow redirects: true allow zero byte data: true allow chunked encoding: true proxy auth: www auth: 二、siege的使用 举例说明: 50个用户(每次并发量,注意不是每秒并发量) 重复100次 共产生 50 * 100 = 5000个请求 /usr/local/siege/bin/siege -c 50 -r 100 https://www.abc.com/a.php 50个用户 重复100次 发送GET参数 /usr/local/siege/bin/siege -c 50 -r 100 https://www.abc.com/a.php?name=zhangsan 50个用户 重复100次 发送POST参数 (注意引号) /usr/local/siege/bin/siege -c 50 -r 100 "https://www.abc.com/a.php POST name=zhangsan" 50个用户 重复100次 发送POST参数(从文件中读取) /usr/local/siege/bin/siege -c 50 -r 100 "https://www.abc.com/a.php POST < /root/ab_test/post.xml" 另外还有发送时间参数等 详情请man 或 siege -h siege报表解析,请man查看,暂略(有点累了,不想写了。。。。。)。 常见问题见:http://www.joedog.org/siege-faq/ 原文地址 http://blog.csdn.net/yangzhenzhen/article/details/8904746

(工作小记)phpredis Redis::SERIALIZER_IGBINARY 自增字段

最近项目中的统计出现了问题,统计数使用redis的incr 自增。修复数据后使用set xxx value 将新的数据替换老数据 发现set更新后数据又从1开始重新增加 最后发现问题出在 [php]$this->setOption ( \Redis::OPT_SERIALIZER, \Redis::SERIALIZER_IGBINARY );[/php] Redis::SERIALIZER_IGBINARY这个参数 Redis::SERIALIZER_IGBINARY [php] $redis->set("a", 3); $redis->incr("a"); // 1 echo $redis->get("a"); // output 1 [/php] Redis::SERIALIZER_PHP [php] $redis->set("a", 3); $redis->incr("a"); // false echo $redis->get("a"); // output 3 [/php] 解决方案 在保存之前临时将参数改为Redis::SERIALIZER_NONE 取消序列化 最后别忘了把它改回来 参考 https://github.com/phpredis/phpredis/issues/246