def post(self): user = users.get_current_user() if user: project_key = self.request.get('project_key') if project_key <> '': key = db.Key(project_key) q = FunctionPointProject.gql("WHERE __key__ =:1", key) projects = q.fetch(1) project = None for p in projects: project = p break functions = list_functions(project_key) return self.response.out.write(json.write({'project':project.to_dict(), 'items':functions})) else: err = {'error':common.message('project_not_selected')} return self.response.out.write(json.write(err)) else: err = {'error':common.message('login_err',common.AppSettings('/fp'))} return self.response.out.write(json.write(err)) err = {'error':'Unknown Error'} return self.response.out.write(json.write(err))
def preset_create(request): if request.method == "POST": form = PresetForm(request.POST, request.FILES) if form.is_valid(): response = HttpResponse(mimetype="application/x-bzip-compressed-tar") response["Content-Disposition"] = "attachment; filename=%s.tar.bz2" % form.cleaned_data["short_name"] tar = tarfile.open(fileobj=response, mode="w:bz2") json = StringIO.StringIO() json.write(form.preset_json.encode("utf-8")) json.seek(0) info = tarfile.TarInfo(name=form.cleaned_data["short_name"] + ".json") info.size = len(json.getvalue()) tar.addfile(info, fileobj=json) icon = StringIO.StringIO() icon.write(request.FILES["icon"].read()) icon.seek(0) info = tarfile.TarInfo(name=request.FILES["icon"].name) info.size = request.FILES["icon"].size tar.addfile(info, fileobj=icon) tar.close() return response else: form = PresetForm() return render(request, "presets/create.html", { "form": form, })
def post(self): user = users.get_current_user() if user: project_key = self.request.get('project_key') function_type = self.request.get('function_type') if project_key <> '': func_entity = FunctionEntity( project_key=project_key, function_type=function_type, function_name='', measurement_index1=0, measurement_index2=0, sort_order=99, ); func_entity.put() return self.response.out.write(json.write(func_entity.to_dict())) else: err = {'error':common.message('project_not_selected')} return self.response.out.write(json.write(err)) else: err = {'error':common.message('login_err',common.AppSettings('/fp'))} return self.response.out.write(json.write(err)) err = {'error':'Unknown Error'} return self.response.out.write(json.write(err))
def post(self): user = users.get_current_user() if user: key_str = self.request.get('key') key = db.Key(key_str); func_entity = None q = FunctionEntity.gql("WHERE __key__ = :1", key) results = q.fetch(1) for result in results: result.delete() func_entity = result if func_entity: return self.response.out.write(json.write({'key':key_str})) else: err = {'error':'Entity is not found.'} return self.response.out.write(json.write(err)) else: err = {'error':common.message('login_err',common.AppSettings('/fp'))} return self.response.out.write(json.write(err)) err = {'error':'Unknown Error'} return self.response.out.write(json.write(err))
def consult_form(request): errors = {} if request.method == "POST": program_id = request.POST.get("program", None) if not request.POST.get("phone"): errors["phone"] = u"Введите номер телефона" if not request.POST.get("name"): errors["name"] = u"Введите имя" if request.POST.get("email"): if not validateEmail(request.POST.get("email")): errors["email"] = u"Введите email правильно" if errors: return HttpResponse(json.write({"errors": errors}), mimetype="application/json") portal = lfc.utils.get_portal() if program_id: program = Program.objects.get(id=program_id) subject = u"Заявка со страницы программы " + program.title message = u"Заявка со страницы программы " + program.title + " http://kidness.ru/" + program.get_absolute_url() + "\n" else: subject = u"Заявка" message = u"Заявка со страницы " + request.POST.get("url", "") + u"\n" message += u"Имя: " + request.POST.get("name") + u"\n" message += u"Телефон: " + request.POST.get("phone") + u"\n" message += u"Email: " + request.POST.get("email", "-") + u"\n" if request.POST.get("email", False): if request.POST.get("getnews", False): message += u"хочет плучать новости по email\n" else: message += u"НЕ хочет плучать новости по email\n" message += u"Комментарий: " + request.POST.get("comment", "-") + u"\n" from_email = portal.from_email recipient_list = portal.get_notification_emails() send_mail(subject, message, from_email, recipient_list, fail_silently=False) return HttpResponse(json.write({ }), mimetype="application/json")
def GET(self): input = web.input() web.write("Content-type: text/plain\n\n") stacks=json.read(input["stacks"]) payouts=json.read(input["payouts"]) icm = ICM(stacks,payouts) print json.write(icm.equities)
def post(self): user = users.get_current_user() if user: project_key = self.request.get('project_key') key_str = self.request.get('key') q = FunctionEntity.gql("WHERE project_key=:1 ORDER BY sort_order", project_key) functions = q.fetch(MAX_FUNCTION) for i, func in enumerate(functions): if key_str == str(func.key()): if i > 0: tmp = functions[i - 1] functions[i - 1] = functions[i] functions[i] = tmp functions[i - 1].put() functions[i].put() break sort_order = 1 for func in functions: func.sort_order = sort_order func.put() sort_order += 1 result = list_functions(project_key) return self.response.out.write(json.write({'items':result})) else: err = {'error':common.message('login_err',common.AppSettings('/fp'))} return self.response.out.write(json.write(err)) err = {'error':'Unknown Error'} return self.response.out.write(json.write(err))
def post(self): user = users.get_current_user() if user: system_name = self.request.get('project_profile_system_name') application_name = self.request.get('project_profile_application_name') mesurement_type = self.request.get('project_profile_mesurement_type') project = FunctionPointProject(system_name=system_name, application_name=application_name, mesurement_type=mesurement_type, data_communications=0, distoributed_processing=0, performance=0, heavily_used_configuration=0, transaction_rate=0, online_data_entry=0, enduser_efficiency=0, online_update=0, complex_processing=0, reusability=0, installation_ease=0, operational_ease=0, multiple_sites=0, facilitate_change=0, sort_order=0, ) project.put(); return self.response.out.write(json.write(project.to_dict())) else: err = {'error':common.message('login_err',common.AppSettings('/fp'))} return self.response.out.write(json.write(err)) err = {'error':'Unknown Error'} return self.response.out.write(json.write(err))
def _q_index(self, request): request = quixote.get_request() response = quixote.get_response() if request.get_method() in ('POST', 'PUT'): if '_json' in request.form: ret = {} try: changes = json.read(request.form['_json']) for n,v in changes.items(): ret[n] = self.set_meta(n, v) ref = request.get_environ('HTTP_REFERER') if ref is not None: p = self.image.pic() response.redirect(ref + '#pic%d' % p.id) http.json_response() return json.write(ret) except json.ReadException: raise QueryError('badly formatted JSON') response.set_status(204) # no content return '' meta = self.get_meta() http.json_response() return json.write(meta)
def check_modules(): try: from ConfigParser import ConfigParser import cherrypy import cgi import logging import mimetypes import os import re import random import signal, errno import sys import subprocess import shutil from subprocess import call import StringIO import stat import urllib import subprocess from Cheetah.Template import Template import tempfile import datetime,time import json import getpass from twisted.plugin import getPlugins, IPlugin try: #This bit here is to handle backwards compatibility with python-json modules. The .write and .dumps methods work analagously as far as I can tell json.write("test") except AttributeError, ae: json.dumps("test") try: from hashlib import md5 except ImportError, ie: from md5 import md5
def post(self): user = users.get_current_user() if user: key_str = self.request.get('project_profile_key') system_name = self.request.get('project_profile_system_name') application_name = self.request.get('project_profile_application_name') mesurement_type = self.request.get('project_profile_mesurement_type') key = db.Key(key_str) q = FunctionPointProject.gql("WHERE __key__ =:1", key) projects = q.fetch(1) for project in projects: project.system_name = system_name project.application_name = application_name project.mesurement_type = mesurement_type project.put() projects = list_projects(user) return self.response.out.write(json.write({'items':projects})) else: err = {'error':common.message('login_err',common.AppSettings('/fp'))} return self.response.out.write(json.write(err)) err = {'error':'Unknown Error'} return self.response.out.write(json.write(err))
def commentsubmit(req): sdb = boto.connect_sdb(AWSKey, AWSSecret) domain = sdb.get_domain('comment') form = req.form imagekey = form['imagekey'] user = form['commentuser'] cmt = form['comment'] import uuid from time import strftime guid = str(uuid.uuid1()) item = domain.new_item(guid) item['submituser'] = user item['imagekey'] = imagekey item['comment'] = cmt item['status'] = "processing" item['submitdate'] = strftime("%Y-%m-%dT%H:%M:%S") item.save() sqsconn = SQSConnection(AWSKey, AWSSecret) q = sqsconn.get_queue('commentprocess') request = {} request['commentkey'] = guid request['submitdate'] = strftime("%Y-%m-%dT%H:%M:%S") request['comment'] = str(cmt) request['submituser'] = str(user) m = RawMessage() m.set_body(json.write(request)) status = q.write(m) response = {} if status==m: response['complete'] = True response['commentkey'] = guid else: response['complete'] = False return json.write(response)
def post(self): user = users.get_current_user() if user: projects = list_projects(user) return self.response.out.write(json.write({'items':projects})) else: err = {'error':common.message('login_err',common.AppSettings('/fp'))} return self.response.out.write(json.write(err))
def redo(req,path,jsoncallback): res = {} res['good'],res['path'] = realpath(req,path) if not res['good']: res['err'] = res['path'] syslog.syslog('ftpmon: ' + res['path']) return "%s(%s)" % (jsoncallback,json.write(res)) res['good'],res['err'] = cleanUp(res['path'],'proxy') return "%s(%s)" % (jsoncallback,json.write(res))
def toJson(self,extranames=1): if extranames: if self.jsontext: return self.jsontext else: data = self.toPython(forcesig=1) self.jsontext = json.write(data) return self.jsontext else: return json.write(self.toPython(nosig=1))
def submitimage(req): sdb = boto.connect_sdb(AWSKey, AWSSecret) domain = sdb.get_domain('picture') form = req.form tags = str(form['tags']) user = str(form['submituser']) description = str(form['description']) fileitem = form['image'] import uuid from time import strftime guid = str(uuid.uuid1()) item = domain.new_item(guid) try: # Windows needs stdio set for binary mode. import msvcrt msvcrt.setmode (0, os.O_BINARY) # stdin = 0 msvcrt.setmode (1, os.O_BINARY) # stdout = 1 except ImportError: pass # strip leading path from file name to avoid directory traversal attacks fname = os.path.basename(fileitem.filename) # build absolute path to files directory dir_path = os.path.join(os.path.dirname(req.filename), 'files') open(os.path.join(dir_path, fname), 'wb').write(fileitem.file.read()) from boto.s3.connection import S3Connection conn = S3Connection(AWSKey, AWSSecret) bucket = conn.get_bucket('theimageproject') from boto.s3.key import Key k = Key(bucket) k.key = guid + ".jpg" k.set_contents_from_filename(os.path.join(dir_path, fname)) curtime = strftime("%Y-%m-%dT%H:%M:%S") item['description'] = description item['submituser'] = user item['submitdate'] = curtime item['rating'] = 0 item['ratingcount'] = 0 item['ratesort'] = "%s%s" % (0, curtime) item['status'] = "processing" item['tag'] = tags.split(',') item.save() sqsconn = SQSConnection(AWSKey, AWSSecret) q = sqsconn.get_queue('imageprocess') request = {} request['imagekey'] = guid request['submitdate'] = curtime m = RawMessage() m.set_body(json.write(request)) status = q.write(m) response = {} if status==m: response['success'] = True response['imagekey'] = guid else: response['complete'] = False return json.write(response)
def post(self): calc_mode = self.request.get('calc_mode') num = self.request.get('num') cocomo = None if (calc_mode in ('kdsi','effort')) and re.match(r'^[0-9]+[\.]{0,1}[0-9]*$',num): cocomo = Cocomo(calc_mode,kdsi=float(num),effort=float(num)) #logging.warn(json.write(cocomo.to_dict())) return self.response.out.write(json.write(cocomo.to_dict())) return self.response.out.write(json.write({'error':u'入力項目に誤りがあります.'}))
def post(self): user = users.get_current_user() if user: key_str = self.request.get('project_profile_key') if key_str.strip() == '': err = {'error':common.message('project_not_selected')} return self.response.out.write(json.write(err)) # data_communications = self.request.get('data_communications') distoributed_processing = self.request.get('distoributed_processing') performance = self.request.get('performance') heavily_used_configuration = self.request.get('heavily_used_configuration') transaction_rate = self.request.get('transaction_rate') online_data_entry = self.request.get('online_data_entry') enduser_efficiency = self.request.get('enduser_efficiency') online_update = self.request.get('online_update') complex_processing = self.request.get('complex_processing') reusability = self.request.get('reusability') installation_ease = self.request.get('installation_ease') operational_ease = self.request.get('operational_ease') multiple_sites = self.request.get('multiple_sites') facilitate_change = self.request.get('facilitate_change') # key = db.Key(key_str) q = FunctionPointProject.gql("WHERE __key__ =:1", key) projects = q.fetch(1) for project in projects: project.data_communications = to_idx(data_communications) project.distoributed_processing = to_idx(distoributed_processing) project.performance = to_idx(performance) project.heavily_used_configuration = to_idx(heavily_used_configuration) project.transaction_rate = to_idx(transaction_rate) project.online_data_entry = to_idx(online_data_entry) project.enduser_efficiency = to_idx(enduser_efficiency) project.online_update = to_idx(online_update) project.complex_processing = to_idx(complex_processing) project.reusability = to_idx(reusability) project.installation_ease = to_idx(installation_ease) project.operational_ease = to_idx(operational_ease) project.multiple_sites = to_idx(multiple_sites) project.facilitate_change = to_idx(facilitate_change) project.put() return self.response.out.write(json.write(project.to_dict())) else: err = {'error':common.message('login_err',common.AppSettings('/fp'))} return self.response.out.write(json.write(err)) err = {'error':'Unknown Error'} return self.response.out.write(json.write(err))
def backup_month(start_tick,stop_tick,yyyymm): """备份一个月的短信""" conn=sqlite3.connect(DB_FILENAME) curr=conn.cursor() sql=SQL_GETSMS%{ 'start_tick':start_tick, 'stop_tick':stop_tick,} #print sql curr.execute(sql) dataset=curr.fetchall() savedset=set() if os.path.exists(INBOX_FILENAME%{'yyyymm':yyyymm}): fr_inbox=open(INBOX_FILENAME%{'yyyymm':yyyymm},'r') fr_sent=open(SENT_FILENAME%{'yyyymm':yyyymm},'r') for line in fr_inbox.xreadlines(): msgdict=json.read(line) savedset.add(msgdict['msgid']) for line in fr_sent.xreadlines(): msgdict=json.read(line) savedset.add(msgdict['msgid']) fr_inbox.close() fr_sent.close() msglist=[] fw_inbox=open(INBOX_FILENAME%{'yyyymm':yyyymm},'a+') fw_sent=open(SENT_FILENAME%{'yyyymm':yyyymm},'a+') #print 'len(dataset)=',len(dataset) for (starttime,outgoing,freetext,remoteuid) in dataset: #print repr(outgoing),repr(freetext),repr(starttime) msgdict={ 'msg':freetext.encode('utf-8'), 'msgid':'%d-%s-%d'%(starttime, remoteuid.encode('utf-8'),len(freetext)), 'ts':starttime, } if msgdict['msgid'] in savedset: continue if outgoing==1: msgdict['tfrom']=LOCAL_PHONENUMBER msgdict['tto']=remoteuid.encode('utf-8') fw_sent.write(json.write(msgdict)+'\n') elif outgoing==0: msgdict['tto']=LOCAL_PHONENUMBER msgdict['tfrom']=remoteuid.encode('utf-8') fw_inbox.write(json.write(msgdict)+'\n') else: raise ValueError('Unknow outgoing=%d'%outgoing) #print msgdict # do it fw_inbox.close() fw_sent.close() curr.close() conn.close() return
def _run(self): """really to del. """ self.checkArgvs() # try: self.move_file() self.stdout.write("RESULT###%s%s"%(json.write({"result":1, "msg":"", "aux":{}, "v":VERSION}), os.linesep)) self.stdout.flush() except Exception, e: self.stdout.write("RESULT###%s%s"%(json.write({"result":403, "msg":str(e), "aux":{}, "v":VERSION}), os.linesep)) self.stdout.flush()
def json_parse(obj): ty = type(obj) if ty is types.ListType or ty is types.TupleType: results = [] for val in obj: if isinstance(val, User) or isinstance(val, Group) or isinstance(val, File): results.append(val.get_dict()) else: results.append(val) json.write(results) else: json.write(obj)
def main(): t = Tetris(); inplay = True; score = 0 totalscore = 0 #while inplay: piece = random.choice(['i','j','l','o','s','t','z']) pos = random.choice(range(10)) degrees = random.choice([0,90,180,270]) #inplay, score = t.dropPiece(pos,piece,degrees) inplay, score = t.dropPiece(5,'l',90) inplay, score = t.dropPiece(1,'o',0) inplay, score = t.dropPiece(0,'t',0) inplay, score = t.dropPiece(1,'i',0) inplay, score = t.dropPiece(8,'l',180) inplay, score = t.dropPiece(0,'j',270) inplay, score = t.dropPiece(3,'o',0) inplay, score = t.dropPiece(0,'z',0) inplay, score = t.dropPiece(6,'i',90) inplay, score = t.dropPiece(7,'z',0) inplay, score = t.dropPiece(0,'o',0) inplay, score = t.dropPiece(7,'t',180) inplay, score = t.dropPiece(7,'t',180) inplay, score = t.dropPiece(3,'s',90) inplay, score = t.dropPiece(4,'s',0) inplay, score = t.dropPiece(0,'s',90) inplay, score = t.dropPiece(2,'t',270) inplay, score = t.dropPiece(3,'j',90) inplay, score = t.dropPiece(7,'l',0) inplay, score = t.dropPiece(7,'z',0) inplay, score = t.dropPiece(6,'j',180) inplay, score = t.dropPiece(7,'z',0) inplay, score = t.dropPiece(2,'o',0) inplay, score = t.dropPiece(7,'l',90) inplay, score = t.dropPiece(3,'l',270) inplay, score = t.dropPiece(7,'z',0) totalscore += score print "======================" t.printBoard() print json.write(t.gameResults) print "totalscore: ", totalscore
def main(): #g = json.read('{ "piece": [".j", ".j", "jj"], "dropTo": 2, "left": 5, "deleteRows": [] }') #game(); g = {}; #{"piece": [], "dropTo": -1, "left": -1, "deleteRows": []} g['piece'] =[".j", ".j", "jj"] g['dropTo'] = 2; g['left'] = 5 g['deleteRows'] = [1,2,3] game = [] game.append(g) print json.write(game);
def delete(req,path,jsoncallback): res = {} res['good'],res['path'] = realpath(req,path) if not res['good']: res['err'] = res['path'] return "%s(%s)" % (jsoncallback,json.write(res)) files = [] for file in locate("*",res['path']): try: os.remove(file) except OSError, s: res['err'] = s syslog.syslog('ftpmon/delete: ' + s) return "%s(%s)" % (jsoncallback,json.write(res))
def run(self): """really to do. """ self.check_argvs() try: code, info=td_osinfo.OSstatus(self.job).run() if code: self.stdout.write("RESULT###%s%s"%(json.write({"result":1, "msg":"", "aux":info}), os.linesep)) self.stdout.flush() else: self.stdout.write("RESULT###%s%s"%(json.write({"result":401, "msg":"", "aux":info}), os.linesep)) self.stdout.flush() except Exception, e: self.stdout.write("RESULT###%s%s"%(json.write({"result":402, "msg":str(e), "aux":{}}), os.linesep)) self.stdout.flush()
def set(self, values): self.__condition.acquire() try: self.__open_for_writing() for key, value in values.items(): version = self.__version + 1 if self.__update(key, value, version, version): self.__file.write(("%d\t%s\t%s\n" % ( version, json.write(key), json.write(value))).encode("utf-8")) self.__file.flush() finally: self.__condition.notifyAll() self.__condition.release()
def run(self): #print type(self.distribution) #for i in sorted(dir(self.distribution)): #if i.startswith("_"): #continue ###print "%s: %r" % (i, self.__getattr__(i)) #print "%s" % i data = { "name": self.distribution.get_name(), "version": self.distribution.get_version(), "author": "%s <%s>" % (self.distribution.get_author(), self.distribution.get_author_email()), "description": self.distribution.get_description(), "license": self.distribution.get_license(), "url": self.distribution.get_url(), } # If there are python C/extension modules, we'll want to build a native # arch package. if self.distribution.has_ext_modules(): data["architecture"] = "native" else: data["architecture"] = "all" # end if final_deps = [] if getattr(self.distribution, 'install_requires', None): for dep in pkg_resources.parse_requirements(self.distribution.install_requires): # add all defined specs to the dependecy list separately. if dep.specs: for operator, version in dep.specs: final_deps.append("%s %s %s" % ( dep.project_name, "=" if operator == "==" else operator, version )) else: final_deps.append(dep.project_name) data["dependencies"] = final_deps #print json.dumps(data, indent=2) try: print json.dumps(data, indent=2) except AttributeError, e: # For Python 2.5 and Debian's python-json print json.write(data)
def send(self, request): request["jsonrpc"] = "2.0" self.setActionForId(request['id'], request['method']) formattedJson = json.write(request) print "[SOCKET] Sending " + formattedJson self.socket.send(formattedJson)
def json(self): schedules = Schedule.find_all() output = [] for schedule in schedules: if not schedule.time_slot.heading: row = {} speakers = schedule.event.computed_speakers() speaker_emails = schedule.event.computed_speaker_emails() row['Id'] = schedule.id row['Event'] = schedule.event_id row['Title'] = schedule.event.computed_title() row['Room Name'] = schedule.location.display_name row['Start'] = str(schedule.time_slot.start_time) row['Duration'] = str(schedule.time_slot.end_time - schedule.time_slot.start_time) if speakers: row['Presenters'] = ','.join(speakers) if speaker_emails: row['Presenter_emails'] = ','.join(speaker_emails) row['Description'] = schedule.event.computed_abstract() if schedule.event.proposal: row['URL'] = h.url_for(qualified=True, controller='schedule', action='view_talk', id=schedule.event.proposal_id) output.append(row) response.charset = 'utf8' response.headers['content-type'] = 'application/json; charset=utf8' response.headers.add('content-transfer-encoding', 'binary') response.headers.add('Pragma', 'cache') response.headers.add('Cache-Control', 'max-age=3600,public') return json.write(output)
def run( self ): incoming = Capture(INCOMING) incoming.start() outgoing = Capture(OUTGOING) outgoing.start() while True: icounter=incoming.counter.getCounter() ocounter=outgoing.counter.getCounter() f = open(stat_file, mode='w') response={} nrecv, ndrop, nifdrop = incoming.getStats() response['nifdrop'] = nifdrop response['ndrop'] = ndrop response['nrecv'] = nrecv nrecv, ndrop, nifdrop = outgoing.getStats() response['nifdrop'] += nifdrop response['ndrop'] += ndrop response['nrecv'] += nrecv response['time'] = time.time() response['outgoing'] = ocounter response['incoming'] = icounter response['iface'] = iface f.write(json.write(response)) f.close() time.sleep(cycle_time)
def json_dump(data): """ Save data using available JSON tools. """ if OLD_SUGAR_SYSTEM is True: return json.write(data) else: _io = StringIO() jdump(data, _io) return _io.getvalue()
def json_dump(data): ''' Save data using available JSON tools. ''' if OLD_SUGAR_SYSTEM is True: return json.write(data) else: io = StringIO() jdump(data, io) return io.getvalue()
def post(self): user = users.get_current_user() if user: key_str = self.request.get('key') function_name = self.request.get('function_name') function_category = self.request.get('function_category') measurement_index1_str = self.request.get('measurement_index1') measurement_index2_str = self.request.get('measurement_index2') try: measurement_index1 = int(measurement_index1_str.strip()) measurement_index2 = int(measurement_index2_str.strip()) except: err = {'error': 'Invalid number.'} return self.response.out.write(json.write(err)) key = db.Key(key_str) func_entity = None q = FunctionEntity.gql("WHERE __key__ = :1", key) results = q.fetch(1) for result in results: result.function_name = function_name result.function_category = function_category result.measurement_index1 = measurement_index1 result.measurement_index2 = measurement_index2 result.put() func_entity = result if func_entity: return self.response.out.write( json.write(func_entity.to_dict())) else: err = {'error': 'Entity is not found.'} return self.response.out.write(json.write(err)) else: err = { 'error': common.message('login_err', common.AppSettings('/fp')) } return self.response.out.write(json.write(err)) err = {'error': 'Unknown Error'} return self.response.out.write(json.write(err))
def main(): if len(sys.argv) != 2: usage() try: data = json.read(open("comments-%s.json" % (sys.argv[1])).read()) except: data = getData(sys.argv[1]) open("comments-%s.json" % (sys.argv[1]), "w").write(json.write(data)) printData(data)
def WriteObjectToJsonString(obj): try: return json.write(obj) except UnicodeDecodeError, e: for item in obj: try: obj[item] = obj[item].decode('utf-8') except Exception, e: pass
def send_photo(name, jpeg): msg = {"jpeg": jpeg, "name": name} sock = socket.socket(socket.AF_INET,\ socket.SOCK_STREAM) sock.connect(("192.168.0.2", 9000)) out = sock.makefile("w") out.write(json.write(msg)) out.close()
def send_message(msg): global to_server try: to_server.write(json.write(msg)) to_server.flush() thread_handle_message({"note": u"Message sent!"}) except Exception, ex: print "Connection error", ex to_server = None
def handle(self): print "A new client connected", self.client_address msg = json.read_stream(self.rfile) if "!name" in msg: name = msg["!name"] wlock = threading.Lock() conn_lock.acquire() conn[name] = (wlock, self.wfile) conn_lock.release() print "Client registered (%s)" % name reply = {"ok": u"registered"} self.wfile.write(json.write(reply)) self.wfile.flush() else: reply = {"err": u"invalid name"} self.wfile.write(json.write(reply)) return self.handle_connection(name)
def json_encode(x): "JSON encode a value." try: return json.dumps(x) except AttributeError: pass # for older library versions return json.write(x)
def add_users(pathname="/srv/salt/ceph/rgw/cache", jinja="/srv/salt/ceph/rgw/files/users.j2"): """ Write each user to its own file. """ users = __salt__['slsutil.renderer'](jinja) log.debug("users rendered: {}".format(users)) if users is None or 'realm' not in users: return for realm in users['realm']: for user in users['realm'][realm]: if 'uid' not in user or 'name' not in user: raise ValueError('ERROR: please specify both uid and name') base_cmd = "radosgw-admin user create --uid={uid} --display-name={name}".format( uid=user['uid'], name=user['name'], ) args = '' if 'email' in user: args += " --email=%s" % user['email'] if 'system' in user and user['system'] is True: args += " --system" if 'access_key' in user: args += " --access-key=%s" % user['access_key'] if 'secret' in user: args += " --secret=%s" % user['secret'] command = base_cmd + args proc = Popen(command.split(), stdout=PIPE, stderr=PIPE) filename = "{}/user.{}.json".format(pathname, user['uid']) with open(filename, "w") as json: for line in proc.stdout: json.write(line) for line in proc.stderr: log.info("stderr: {}".format(line)) proc.wait()
def do_update(self, params): """ @param params: @return: """ if not self.__check_login(): raise Exception('Login error') json_data = json.write(params) return self.post('update', element=json_data)
class PokerEvalWebService: def GET(self): input = web.input() web.header("Content-Type", "text/plain") defaultParams = { "game": "holdem", "pockets": [], "board": [], "dead": [], "iterations": 10000 } kwargs = defaultParams jsonp = None for key in input: value = input[key] if key == "jsoncallback": jsonp = value elif key in ["game", "pockets", "board", "dead", "iterations"]: kwargs[key] = json.read(value) cards = [] for pocket in kwargs["pockets"]: cards.extend(pocket) cards.extend(kwargs["board"]) cards.extend(kwargs["dead"]) duplicate = set( filter(lambda card: (card != "__" and cards.count(card) > 1), cards)) if len(duplicate) > 0: poker_eval_result = { "error": "duplicate cards: %s" % string.join(duplicate) } else: params = apply_game_params(**kwargs) try: poker_eval_result = PokerEval().poker_eval(**params) except Exception, e: poker_eval_result = {"error": str(e)} if jsonp: result = "%s(%s)" % (jsonp, json.write(poker_eval_result)) else: result = json.write(poker_eval_result) print result
def write_file(self, file_path): # Writes the game state to a file. game_data = self._game.get_game_state() file_data = ['Implode save game', [1, 0], game_data] content = json.write(file_data) last_game_path = self._get_last_game_path() for path in (file_path, last_game_path): f = file(path, 'wt') f.write(content) f.close()
def write_file(self, file_path): if not self.metadata['mime_type']: self.metadata['mime_type'] = 'text/plain' fd = open(file_path, 'w') try: text = json.write(self.data) fd.write(text) print "wrote %s" % text finally: fd.close()
def feedtitle(request): if not "url" in request.GET: return HttpResponse('""') else: try: #FIXME: do not make http-calls in frontend return HttpResponse(json.write( feedparser.parse(request.GET['url']).feed.title), mimetype="text/plain") except Exception, e: #404, not a feed, etc. return HttpResponse(repr(e))
def run(self): #print type(self.distribution) #for i in sorted(dir(self.distribution)): #if i.startswith("_"): #continue ###print "%s: %r" % (i, self.__getattr__(i)) #print "%s" % i data = { "name": self.distribution.get_name(), "version": self.distribution.get_version(), "author": "%s <%s>" % (self.distribution.get_author(), self.distribution.get_author_email()), "description": self.distribution.get_description(), "license": self.distribution.get_license(), "url": self.distribution.get_url(), } # If there are python C/extension modules, we'll want to build a native # arch package. if self.distribution.has_ext_modules(): data["architecture"] = "native" else: data["architecture"] = "all" # end if final_deps = [] if getattr(self.distribution, 'install_requires', None): for dep in pkg_resources.parse_requirements( self.distribution.install_requires): # add all defined specs to the dependecy list separately. if dep.specs: for operator, version in dep.specs: final_deps.append( "%s %s %s" % (dep.project_name, "=" if operator == "==" else operator, version)) else: final_deps.append(dep.project_name) data["dependencies"] = final_deps #print json.dumps(data, indent=2) try: print(json.dumps(data, indent=2)) except AttributeError as e: # For Python 2.5 and Debian's python-json print(json.write(data))
def get(self): """Call the appropriate handler based on the path of the HTTP request.""" #self.response.out.write(self.request.path) if not self._isValidSignature(): self.response.out.write(json.write({})) return if self.request.path.startswith('/gifts'): self._handleGifts() elif self.request.path.startswith('/giftTransactions'): self._handleGiftTransactions()
def do_create(self, entity, params): """ @param entity: @param params: @return: """ if not self.__check_login(): raise Exception('Login error') json_data = json.write(params) return self.post('create', elementType=entity, element=json_data)
def testWriteComplexArray(self): obj = [{ "name": "Patrick", "age": 44, "Employed?": True, "Female?": False, "grandchildren": None }, "used", "abused", "confused", 1, 2, [3, 4, 5]] self.assertEqual( '[{"Female?":false,"age":44,"name":"Patrick","grandchildren":null,"Employed?":true},"used","abused","confused",1,2,[3,4,5]]', _removeWhitespace(json.write(obj)))
def add_users(pathname="/srv/salt/ceph/rgw/cache"): """ Write each user to its own file """ if 'rgw_configurations' not in __pillar__: return for role in __pillar__['rgw_configurations']: for user in __pillar__['rgw_configurations'][role]['users']: if 'uid' not in user or 'name' not in user: raise ValueError('ERROR: please specify both uid and name') base_cmd = "radosgw-admin user create --uid={uid} --display-name={name}".format( uid=user['uid'], name=user['name'], ) args = '' if 'email' in user: args += " --email=%s" % user['email'] if 'system' in user and user['system'] is True: args += " --system" if 'access_key' in user: args += " --access-key=%s" % user['access_key'] if 'secret' in user: args += " --secret=%s" % user['secret'] command = base_cmd + args proc = Popen(command.split(), stdout=PIPE, stderr=PIPE) filename = "{}/user.{}.json".format(pathname, user['uid']) with open(filename, "w") as json: for line in proc.stdout: json.write(line) for line in proc.stderr: log.info("stderr: {}".format(line)) proc.wait()
def get(self): user = users.get_current_user() if user: docs = SavedDoc.gql('WHERE owner = :1', user).fetch(100) data = [] for doc in docs: # find the current revision if doc.hash != "": revs = DocRevision.gql( "WHERE hash = :1 ORDER BY version DESC", doc.hash).fetch(1) for rev in revs: data.append(rev.infoJSON()) self.response.out.write(json.write(data)) else: self.response.out.write(json.write({'error': "no_login"}))
def share_with_users(self, path, users): url = "%s/api/share/" % (self.server_url) cmd = {"version" : 1, "directory" : path, "share_to_users" : users} postdata = urllib.urlencode({"cmd" : json.write(cmd), "uid" : self.username, "password" : self.password}) req = urllib2.Request(url, postdata) result = self._open(req).read() if result != "OK": raise Exception("Share attempt failed: %s" % result)
def test_read_json(self): """JsonOperation 类读取 json 文件测试函数,测试用例包括:正常读取/文件不存在/文件格式不是json""" assert self.js.read_json() is not None # 删除文件使文件不存在 path = '../vplx/map_config.json' os.remove(path) # json config 初创需要同步后才能执行之后的操作,不然抛出SystemExit with pytest.raises(SystemExit) as exsinfo: self.js.read_json() assert exsinfo.type == SystemExit # assert self.js.read_json() == json_dict # 破坏 json 正确结构 with open(path, 'a') as json: json.write('ahdfjksj') with pytest.raises(SystemExit) as exsinfo: self.js.read_json() with patch('builtins.print') as terminal_print: terminal_print.assert_called_with('Failed to read json file.') assert exsinfo.type == SystemExit # 删除错误文件 os.remove(path)
def GetReturnJSON(file, type): if type== 'image': obj= { 'state': 'SUCCESS', 'url': '/ueupload/illustration/'+ file.name, 'title': file.name, 'original': file.name } else: obj= {} string= json.write(obj) return string
def run(self): data = { "name": self.distribution.get_name(), "version": self.distribution.get_version(), "author": u("%s <%s>") % ( u(self.distribution.get_author()), u(self.distribution.get_author_email()), ), "description": self.distribution.get_description(), "license": self.distribution.get_license(), "url": self.distribution.get_url(), } if self.distribution.has_ext_modules(): data["architecture"] = "native" else: data["architecture"] = "all" final_deps = [] if self.load_requirements_txt: requirement = open(self.requirements_txt).readlines() for dep in pkg_resources.parse_requirements(requirement): final_deps.extend(self.process_dep(dep)) else: if getattr(self.distribution, 'install_requires', None): for dep in pkg_resources.parse_requirements( self.distribution.install_requires): final_deps.extend(self.process_dep(dep)) data["dependencies"] = final_deps output = open(self.output, "w") if hasattr(json, 'dumps'): def default_to_str(obj): """ Fall back to using __str__ if possible """ # This checks if the class of obj defines __str__ itself, # so we don't fall back to an inherited __str__ method. if "__str__" in type(obj).__dict__: return str(obj) return json.JSONEncoder.default(self, obj) output.write(json.dumps(data, indent=2, default=default_to_str)) else: # For Python 2.5 and Debian's python-json output.write(json.write(data))
def initialize_widget(self): self.get_form()._add_js_file('textbox.js') self.get_form()._add_js_file('prototype-1.2.0.js') sync_with = self.get_arg('sync_with', None) if sync_with is not None: import json sync_with.request_notification( 'change', 'mcw_tb_sync_widget(%s, "%s", %s)' % (sync_with.calljs_getvalue(), self.get_html_id(), json.write(self.get_arg('sync_map', False))))
def assignRequest(url, workflow, team, site, era, procversion, activity, lfn): params = { "action": "Assign", "Team" + team: "checked", "SiteWhitelist": site, "SiteBlacklist": [], "MergedLFNBase": lfn, "UnmergedLFNBase": "/store/unmerged", "MinMergeSize": 2147483648, "MaxMergeSize": 4294967296, "MaxMergeEvents": 100000, "maxRSS": 4294967296, "maxVSize": 4294967296, "AcquisitionEra": era, "dashboard": activity, "ProcessingVersion": procversion, "SoftTimeout": 167000, "GracePeriod": 1000, "checkbox" + workflow: "checked" } # Once the AcqEra is a dict, I have to make it a json objet jsonEncodedParams = {} for paramKey in params.keys(): jsonEncodedParams[paramKey] = json.write(params[paramKey]) encodedParams = urllib.urlencode(jsonEncodedParams, False) headers = { "Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain" } conn = httplib.HTTPSConnection(url, cert_file=os.getenv('X509_USER_PROXY'), key_file=os.getenv('X509_USER_PROXY')) conn.request("POST", "/reqmgr/assign/handleAssignmentPage", encodedParams, headers) response = conn.getresponse() if response.status != 200: print 'could not assign request with following parameters:' for item in params.keys(): print item + ": " + str(params[item]) print 'Response from http call:' print 'Status:', response.status, 'Reason:', response.reason print 'Explanation:' data = response.read() print data print "Exiting!" sys.exit(1) conn.close() print 'Assigned workflow:', workflow, 'to site:', site, 'with processing version', procversion return
def check_packages(): try: from ConfigParser import ConfigParser import cherrypy import cgi import logging import mimetypes import os import re import random import signal, errno import sys import subprocess import shutil from subprocess import call import StringIO import stat import urllib import subprocess from Cheetah.Template import Template import tempfile import datetime, time import json import getpass from lib import Models from twisted.plugin import getPlugins, IPlugin try: #This bit here is to handle backwards compatibility with python-json modules. The .write and .dumps methods work analagously as far as I can tell json.write("test") except AttributeError: json.dumps("test") try: from hashlib import md5 except ImportError: from md5 import md5 return True except Exception, e: import sys print "You are missing a requisite package: %s." % str(e) sys.exit(0)
def read(): # os.system('python join.py hosts') file = open('./temp', 'r') file1 = open('./hosts', 'r') file2 = open('./datetime', 'r') open('./json', 'w') json = open('./json', 'a') json.write('{ "告警":[') while 1: json.write("{") line = file.readline().strip() line1 = file1.readline().strip() line2 = file2.readline().strip() # print '"host":'+'"'+line1.strip(), line.strip(),line2.strip()+'"' json.write('"room":' + '"' + line1.strip() + line.strip() + line2.strip() + '"') json.write("},") if not line and not line1 and not line2: break pass json.write("]}") json.close()
def POST(self): # args = simplejson.loads(web.data()) args = json.read(web.data()) json_func = getattr(self, 'json_%s' % args[u"method"]) json_params = args[u"params"] # json_method_id = args[u"id"] result = json_func(json_params) # reuse args to send result back args.pop(u"method") args["result"] = result[0] args["error"] = None # IMPORTANT!! web.header("Content-Type", "text/html; charset=utf-8") return json.write(args)