rabin 6 years ago
parent
commit
298289bf8b
14 changed files with 90 additions and 2088 deletions
  1. 22 0
      .gitignore
  2. 20 72
      LICENSE
  3. 5 2
      README.md
  4. 0 6
      __init__.py
  5. 0 385
      core.py
  6. 0 65
      db.py
  7. 0 72
      demeter/LICENSE
  8. 0 4
      demeter/README.md
  9. 0 647
      model.py
  10. 0 102
      mqtt.py
  11. 0 78
      service.py
  12. 43 291
      setup.py
  13. 0 70
      tcp.py
  14. 0 294
      web.py

+ 22 - 0
.gitignore

@@ -1,2 +1,24 @@
 .DS_Store
+*.mo
+*.egg-info
+*.egg
+*.EGG
+*.EGG-INFO
+.cache
+bin
+build
+develop-eggs
+downloads
+eggs
+fake-eggs
+parts
+dist
+.installed.cfg
+.mr.developer.cfg
+.hg
+.bzr
+.svn
 *.pyc
+*.pyo
+*.tmp*
+.idea

+ 20 - 72
LICENSE

@@ -1,72 +1,20 @@
-Apache License 
-Version 2.0, January 2004 
-http://www.apache.org/licenses/
-TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
-1. Definitions.
-
-"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
-
-"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
-
-"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
-
-"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
-
-"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
-
-"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
-
-"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
-
-"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
-
-"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
-
-"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
-
-2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
-
-3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
-
-4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
-
-(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
-
-(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
-
-(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
-
-(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
-
-You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
-
-5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
-
-6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
-
-7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
-
-8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
-
-9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
-
-END OF TERMS AND CONDITIONS
-
-APPENDIX: How to apply the Apache License to your work.
-
-To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
-
-Copyright [yyyy] [name of copyright owner]
-
-Licensed under the Apache License, Version 2.0 (the "License"); 
-you may not use this file except in compliance with the License. 
-You may obtain a copy of the License at
-
-http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software 
-distributed under the License is distributed on an "AS IS" BASIS, 
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
-See the License for the specific language governing permissions and 
-limitations under the License.
+The MIT License (MIT)
+
+Copyright (c) 2013 Hamza Faran
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ 5 - 2
README.md

@@ -1,4 +1,7 @@
-# demeter核心类库
+# demeter框架
 
 开发语言:python
-框架:gevent+tornado+demeter类
+框架:gevent+tornado+demeter类库
+
+安装:
+pip git+https://github.com/shemic/demeter

+ 0 - 6
__init__.py

@@ -1,6 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
-    demeter init
-    author:rabin
-"""
-__version__ = '1.0.0'

+ 0 - 385
core.py

@@ -1,385 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-"""
-	demeter core
-	name:demeter.py
-	author:rabin
-"""
-import time
-import os
-import signal
-import re
-import sys
-import getopt
-import json
-import ConfigParser
-import subprocess
-class Demeter(object):
-	path = ''
-	config = {}
-	serviceObj = {}
-	modelObj = {}
-	web = ''
-	request = False
-
-	def __new__(self, *args, **kwargs):
-		sys.exit()
-
-	def __init__(self):
-		pass
-
-	@staticmethod
-	def isset(v): 
-		try :
-			type (eval(v))
-		except :
-			return 0
-		else : 
-			return 1
-
-	@classmethod
-	def initConfig(self):
-		self.path = File.path()
-		if self.config == {}:
-			name = 'dev'
-			if 'DEMETER_CONF' in os.environ:
-				name = os.environ['DEMETER_CONF']
-			filename = self.path + 'conf/'+name+'.conf'
-			if File.exists(filename):
-				config = ConfigParser.ConfigParser()
-				config.read(filename)
-
-				for item in config.sections():
-					self.config[item] = self.readConfig(config, item)
-				return True
-			else:
-				print filename + ' is not exists'
-				sys.exit()
-
-	@staticmethod
-	def readConfig(config, type):
-		value = config.options(type)
-		result = {}
-		for item in value:
-			result[item] = config.get(type, item)
-		return result
-
-	@classmethod
-	def temp(self, key='', name='', value=''):
-		temp = Demeter.path + 'conf/temp.conf'
-		if File.exists(temp):
-			config = ConfigParser.ConfigParser()
-			config.read(temp)
-			if key and name:
-				config.set(key, name, value)
-				config.write(open(temp, 'w'))
-			else:
-				result = {}
-				for item in config.sections():
-					result[item] = self.readConfig(config, item)
-				return result
-
-	@classmethod
-	def echo(self, args):
-		module = self.getObject('pprint')
-		module.pprint(args)
-
-	@classmethod
-	def record(self, key, value):
-		# 记录日志
-		# self.log(key, value)
-		service = self.service('record')
-		service.push(key, value)
-
-	@classmethod
-	def service(self, name):
-		path = 'service.'
-		if name == 'common':
-			path = 'demeter.'
-			name = 'service'
-		service = self.getClass(name, path)
-		return service()
-		"""
-		if name not in self.serviceObj:
-			path = 'service.'
-			if name == 'common':
-				path = 'demeter.'
-				name = 'service'
-			service = self.getClass(name, path)
-			self.serviceObj[name] = service()
-		return self.serviceObj[name]
-		"""
-
-	@classmethod
-	def model(self, table, name='rdb'):
-		name = self.config['db'][name]
-		config = self.config[name]
-		obj = self.getObject('db', 'demeter.')
-		db = getattr(obj, name.capitalize())
-		connect = db(config).get()
-		model = self.getClass(table, 'model.')
-		return model(name, connect, config)
-		"""
-		if table not in self.modelObj:
-			name = self.config['db'][name]
-			config = self.config[name]
-			obj = self.getObject('db', 'demeter.')
-			db = getattr(obj, name.capitalize())
-			connect = db(config).get()
-			model = self.getClass(table, 'model.')
-			self.modelObj[table] =  model(name, connect, config)
-		return self.modelObj[table]
-		"""
-
-	@classmethod
-	def getClass(self, name, path=''):
-		obj = self.getObject(name, path)
-		return getattr(obj, name.capitalize())
-
-	@staticmethod
-	def getObject(name, path = ''):
-		module = __import__(path + name)
-		return getattr(module, name)
-
-	@staticmethod
-	def bool(value):
-		return value == str(True)
-
-	@classmethod
-	def runtime(self, path, file, content=''):
-		path = self.path + 'runtime/' + path + '/'
-		File.mkdir(path)
-		file = path + file
-		if File.exists(file):
-			return False
-		else:
-			File.write(file, content)
-			return True
-
-	@classmethod
-	def webstart(self, name):
-		self.web = name
-		self.webPath = self.path + self.web + '/'
-		self.getObject('main', name + '.')
-
-	@classmethod
-	def md5(self, value, salt=False):
-		module = __import__('md5')
-		md5 = getattr(module, 'new')
-		md5_obj = md5()
-		if salt:
-			if salt == True:
-				salt = self.rand()
-			md5_obj.update(value + salt)
-			return md5_obj.hexdigest() + '_' + salt
-		else:
-			md5_obj.update(value)
-			return md5_obj.hexdigest()
-
-	@staticmethod
-	def rand(length = 4):
-		module = __import__('random')
-		rand = getattr(module, 'randint')
-		salt = ''
-		chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
-		len_chars = len(chars) - 1
-		for i in xrange(length):
-			salt += chars[rand(0, len_chars)]
-		return salt
-	@staticmethod
-	def hour(value):
-		if value < 10:
-			return '0' + str(value)
-		return value
-	@staticmethod
-	def time():
-		return int(time.time())
-
-	@staticmethod
-	def mktime(value, string='%Y-%m-%d %H:%M:%S'):
-		if ' ' in string and ' ' not in value:
-			value = value + ' 00:00:00'
-		return int(time.mktime(time.strptime(value,string)))
-
-	@staticmethod
-	def date(value, string='%Y-%m-%d %H:%M:%S'):
-		module = __import__('datetime')
-		datetime = getattr(module, 'datetime')
-		fromtimestamp = getattr(datetime, 'fromtimestamp')
-		return str(fromtimestamp(value).strftime(string))
-
-	@staticmethod
-	def isJson(value):
-		result = False
-		try:
-			result = json.loads(value)
-		except ValueError:
-			return result
-		return result
-
-	@staticmethod
-	def compressUuid(value):
-		row = value.replace('-', '')
-		code = ''
-		hash = [x for x in "0123456789-abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ"]
-		for i in xrange(10):
-			enbin = "%012d" % int(bin(int(row[i * 3] + row[i * 3 + 1] + row[i * 3 + 2], 16))[2:], 10)
-			code += (hash[int(enbin[0:6], 2)] + hash[int(enbin[6:12], 2)])
-		return code
-
-	@staticmethod
-	def checkMobile(request):
-		if 'Demeter-Mobile' in request.headers:
-			return True
-		userAgent = request.headers['User-Agent']
-		# userAgent = env.get('HTTP_USER_AGENT')
-
-		_long_matches = r'googlebot-mobile|android|avantgo|blackberry|blazer|elaine|hiptop|ip(hone|od)|kindle|midp|mmp|mobile|o2|opera mini|palm( os)?|pda|plucker|pocket|psp|smartphone|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce; (iemobile|ppc)|xiino|maemo|fennec'
-		_long_matches = re.compile(_long_matches, re.IGNORECASE)
-		_short_matches = r'1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-'
-		_short_matches = re.compile(_short_matches, re.IGNORECASE)
-
-		if _long_matches.search(userAgent) != None:
-			return True
-		user_agent = userAgent[0:4]
-		if _short_matches.search(user_agent) != None:
-			return True
-		return False
-
-	@staticmethod
-	def exp(exp, value):
-		if exp:
-			exp = exp.replace('{n}', value)
-			value = str(eval(exp))
-		return value
-
-	@classmethod
-	def curl(self, url):
-		import urllib2
-		req = urllib2.Request(url)
-		response = urllib2.urlopen(req)
-		return response.read()
-
-	@classmethod
-	def error(self, string):
-		from tornado.web import Finish
-		if self.request:
-			self.request.out(string)
-			#self.request.finish()
-			raise Finish()
-		else:
-			print string
-			#os._exit(0)
-
-class File(object):
-
-	@staticmethod
-	def write(file, content):
-		handle = open(file, 'w')
-		handle.write(content)
-		handle.close()
-		Shell.popen('chmod +x ' + file)
-
-	@staticmethod
-	def read(path, name):
-		handle = open(path + name, 'r')
-		content = handle.read()
-		handle.close()
-		return content
-
-	@staticmethod
-	def cur_path():
-		return os.path.split(os.path.realpath(__file__))[0] + '/'
-
-	@staticmethod
-	def path():
-		return os.sys.path[0] + '/'
-
-	@staticmethod
-	def exists(name):
-		return os.path.exists(name)
-
-	@staticmethod
-	def rename(old, new):
-		return os.rename(old, new)
-
-	@staticmethod
-	def remove(file):
-		return os.remove(file)
-
-	@staticmethod
-	def mkdir(path):
-		if File.exists(path) == False:
-			os.mkdir(path)
-		return path
-
-	@staticmethod
-	def mkdirs(path):
-		if File.exists(path) == False:
-			os.makedirs(path)
-		return path
-
-class Shell(object):
-	@staticmethod
-	def popen(command, sub=False, bg=False, timeout=0):
-		string = command
-		if bg == True:
-			command = command + ' 1>/dev/null 2>&1 &'
-
-		if timeout > 0:
-			proc = subprocess.Popen(command,bufsize=0,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True, close_fds=True, preexec_fn = os.setsid)
-			poll_seconds = .250
-			deadline = time.time() + timeout
-			while time.time() < deadline and proc.poll() == None:
-				time.sleep(poll_seconds)
-			if proc.poll() == None:
-				os.killpg(proc.pid, signal.SIGTERM)
-				return 'timeout'
-
-			stdout,stderr = proc.communicate()
-			return stdout
-		elif sub == False:
-			process = os.popen(command)
-			output = process.read()
-			process.close()
-			return output
-		else:
-			popen  = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
-			output = ''
-			print string
-			while True:
-				output = popen.stdout.readline()
-				print output
-				if popen.poll() is not None:
-					break
-			return output
-
-class Check(object):
-	@staticmethod
-	def match(rule, value):
-		if not rule.match(value):
-			return False
-		return True
-
-	@staticmethod
-	def mobile(value):
-		rule = re.compile(r'1\d{10}')
-		return Check.match(rule, value)
-
-	@staticmethod
-	def number(value):
-		try:
-			int(value)
-			return True
-		except ValueError:
-			return False
-
-	@staticmethod
-	def numberFloat(value):
-		try:
-			float(value)
-			return True
-		except ValueError:
-			return False
-
-Demeter.initConfig()

+ 0 - 65
db.py

@@ -1,65 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-"""
-    demeter database
-    name:db.py
-    author:rabin
-"""
-
-class Influxdb(object):
-	instance = None
-	def __new__(cls, *args, **kwd):
-		if Influxdb.instance is None:
-			Influxdb.instance = object.__new__(cls, *args, **kwd)
-		return Influxdb.instance
-
-	def __init__(self, config):
-		influxdb = __import__('influxdb')
-		InfluxDBClient = getattr(influxdb, 'InfluxDBClient')
-		self.connect = InfluxDBClient(config['host'], config['port'], config['username'], config['password'], config['dbname'])
-		self.create(config['dbname'])
-
-	def get(self):
-		return self.connect
-
-	def create(self, name):
-		database = self.connect.get_list_database()
-		self.connect.create_database(name)
-
-
-class Postgresql(object):
-	instance = None
-	def __new__(cls, *args, **kwd):
-		if Postgresql.instance is None:
-			Postgresql.instance = object.__new__(cls, *args, **kwd)
-		return Postgresql.instance
-		
-	def __init__(self, config):
-		psycopg2 = __import__('psycopg2')
-		self.connect = psycopg2.connect(host=config['host'], port=config['port'], user=config['username'], password=config['password'], database=config['dbname'])
-
-	def get(self):
-		return self.connect
-
-	def create(self, name):
-		'psql -U postgres'
-		sql = 'CREATE DATABASE '+name+' WITH OWNER = postgres ENCODING = "UTF8"'
-		return sql
-
-class Mysql(object):
-	instance = None
-	def __new__(cls, *args, **kwd):
-		if Mysql.instance is None:
-			Mysql.instance = object.__new__(cls, *args, **kwd)
-		return Mysql.instance
-		
-	def __init__(self, config):
-		pymysql = __import__('pymysql')
-		self.connect = pymysql.connect(host=config['host'], port=int(config['port']), user=config['username'], password=config['password'], database=config['dbname'])
-
-	def get(self):
-		return self.connect
-
-	def create(self, name):
-		sql = 'CREATE DATABASE '+name+' ENCODING = "UTF8"'
-		return sql

+ 0 - 72
demeter/LICENSE

@@ -1,72 +0,0 @@
-Apache License 
-Version 2.0, January 2004 
-http://www.apache.org/licenses/
-TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
-1. Definitions.
-
-"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
-
-"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
-
-"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
-
-"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
-
-"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
-
-"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
-
-"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
-
-"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
-
-"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
-
-"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
-
-2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
-
-3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
-
-4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
-
-(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
-
-(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
-
-(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
-
-(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
-
-You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
-
-5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
-
-6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
-
-7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
-
-8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
-
-9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
-
-END OF TERMS AND CONDITIONS
-
-APPENDIX: How to apply the Apache License to your work.
-
-To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
-
-Copyright [yyyy] [name of copyright owner]
-
-Licensed under the Apache License, Version 2.0 (the "License"); 
-you may not use this file except in compliance with the License. 
-You may obtain a copy of the License at
-
-http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software 
-distributed under the License is distributed on an "AS IS" BASIS, 
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
-See the License for the specific language governing permissions and 
-limitations under the License.

+ 0 - 4
demeter/README.md

@@ -1,4 +0,0 @@
-# demeter核心类库
-
-开发语言:python
-框架:gevent+tornado+demeter类

+ 0 - 647
model.py

@@ -1,647 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-"""
-    demeter database
-    name:__base__.py
-    author:rabin
-"""
-import os
-import uuid
-import short_url
-import json
-import traceback
-import re
-import math
-from demeter.core import *
-class Model(object):
-	__table__ = ''
-	__comment__ = ''
-	def __init__(self, type, db, config):
-		self.db = db
-		self._type = type
-		self._config = config
-		self._table = self._config['prefix'] + '_' + self.__table__
-		self._set = ''
-		self._bind = {}
-		self._attr = {}
-		self._key = {}
-		self.create()
-
-	def cur(self):
-		return self.db.cursor()
-
-	def query(self, sql, method='select', fetch='fetchall'):
-		cur = self.cur()
-		bind = []
-		if self._set:
-			for key in self._set:
-				self.check(key, self._set[key], self._attr[key])
-				if self._set[key] == 'time':
-					self._set[key] = self.time()
-				elif self._set[key] == 'True':
-					self._set[key] = True
-				elif self._set[key] == 'False':
-					self._set[key] = False
-				elif 'date' in key and type(self._set[key]) != int:
-					self._set[key] = self.mktime(self._set[key])
-				elif self._attr[key].md5:
-					self._set[key] = self.createMd5(self._set[key])
-				bind.append(self._set[key])
-		for value in self._key:
-			if value[0] in self._bind and self._bind[value[0]] != None:
-				val = self._bind[value[0]]
-				if method == 'insert':
-					self.check(value[0], val, self._attr[value[0]])
-				self._attr[value[0]].unset()
-				if type(val) == list and val:
-					for i in val:
-						bind.append(i)
-				else:
-					bind.append(val)
-		if method == 'select' and ';' in sql:
-			temp = sql.split(';')
-			sql = temp[1]
-			totalSql = temp[0]
-			cur.execute(totalSql, bind)
-			Demeter.config['page']['totalNum'] = self.fetch(cur, 'fetchone', 'count')
-			Demeter.config['page']['total'] = int(math.ceil(round(float(Demeter.config['page']['totalNum'])/float(Demeter.config['page']['num']),2)))
-		cur.execute(sql, bind)
-		if method == 'select':
-			return self.fetch(cur, fetch)
-		id = True
-		if method == 'insert':
-			id = cur.fetchone()[0]
-		self.db.commit()
-		self._set = {}
-		return id
-		"""
-		try:
-			
-		except Exception, e:
-			print e.message
-			os._exit(0)
-		"""
-
-
-	def fetch(self, cur, type, method = ''):
-		load = getattr(cur, type)
-		rows = load()
-		if type == 'fetchall':
-			result = []
-			if rows:
-				for key in rows:
-					row = {}
-					i = 0
-					for v in key:
-						row[self._key[i][0]] = v
-						i = i + 1
-					result.append(row)
-		elif method == 'count':
-			return rows[0]
-		else:
-			result = {}
-			i = 0
-			if rows:
-				for key in rows:
-					if not key:
-						key = ''
-					result[self._key[i][0]] = key
-					i = i + 1
-		return result
-
-	def attr(self, method):
-		fields = vars(self.__class__)
-		self._attr = {}
-		self._bind = {}
-		self._key = {}
-		col = (int, str, long, float, unicode, bool, uuid.UUID)
-		for field in fields:
-			if isinstance(fields[field], Fields):
-				self._attr[field] = fields[field]
-				self._key[field] = self._attr[field].getKey()
-				insert = (method == 'insert')
-				update = (insert or method == 'update')
-				if insert and self._attr[field].uuid:
-					self.setUuid(field, col)
-				bind = False
-				val = self._attr[field].getArgv()
-				if val or val == False:
-					bind = True
-				else:
-					val = getattr(self, field)
-					if isinstance(val, col):
-						setattr(self, field, self._attr[field])
-						bind = True
-					elif insert and self._attr[field].default:
-						val = self._attr[field].default
-						bind = True
-						if val == 'time':
-							val = self.time()
-						elif '.' in val:
-							temp = val.split('.')
-							val = Demeter.config[temp[0]][temp[1]]
-					elif method == 'select' and self._attr[field].default and field == 'state':
-						val = self._attr[field].default
-						bind = True
-				if bind and val != None:
-					if type(val) == list:
-						length = len(val)
-						if length <= 1:
-							val = val[0]
-					if insert and self._attr[field].md5:
-						val = self.createMd5(val)
-					if self._attr[field].type == 'boolean' and isinstance(val, (str, unicode)):
-						val = Demeter.bool(val)
-					if type(val) == list:
-						val = tuple(val)
-					self._bind[field] = val
-					self._attr[field].val(self._bind[field])
-					self._attr[field].bind('%s')
-
-		self._key = sorted(self._key.items(), key=lambda d:d[1], reverse = False)
-		Counter().unset()
-
-	def check(self, field, val, attr):
-		if val == 'undefined':
-			self.error(error)
-		if attr.match == 'not':
-			if not val:
-				self.error(field + ' not exists')
-		elif attr.match:
-			if '|' in attr.match:
-				temp = attr.match.split('|')
-				match = temp[0]
-				error = temp[1]
-			else:
-				match = attr.match
-				error = field + ' not match:' + match
-			if hasattr(Check, match):
-				method = getattr(Check, match)
-				result = method(val)
-			else:
-				result = re.search(match, val)
-			if not result:
-				self.error(error)
-
-	def error(self, msg):
-		for value in self._key:
-			if value[0] in self._bind and self._bind[value[0]] != None:
-				self._attr[value[0]].unset()
-		self._set = {}
-		Demeter.error(msg)
-
-	def time(self):
-		return Demeter.time()
-
-	def mktime(self, value):
-		return Demeter.mktime(value)
-
-	def setUuid(self, field, col):
-		id = getattr(self, self._attr[field].uuid)
-		if isinstance(id, col):
-			system = short_url.encode_url(id)
-		else:
-			system = self._attr[field].uuid
-		name = system + '.' + self.__table__
-		result = uuid.uuid5(uuid.uuid1(), name)
-		result = str(result)
-		setattr(self, field, result)
-
-	def createMd5(self, value):
-		return Demeter.md5(value, salt=True)
-
-	def createState(self):
-		if 'create' in self._config:
-			create = Demeter.bool(self._config['create'])
-			if create:
-				return Demeter.runtime(self._type, self.__table__, json.dumps(self._key))
-		return False
-
-	def drop(self):
-		return self.handle('drop')
-
-	def create(self):
-		return self.handle('create')
-
-	def insert(self):
-		return self.handle('insert')
-
-	def update(self, *args, **kwargs):
-		if args:
-			self._set = args[0]
-		else:
-			self._set = kwargs
-		return self.handle('update', set=self._set)
-
-	def delete(self):
-		return self.handle('delete')
-
-	def select(self, type='fetchall',col = '*', order = 'cdate desc', group = '', limit = '0,100', page=False):
-		pageConfig = {}
-		if page and 'page' in Demeter.config:
-			pageConfig['current'] = Demeter.config['page']['current']
-			if page == True:
-				pageConfig['num'] = 15
-			elif 'num' in page:
-				pageConfig['num'] = page['num']
-			Demeter.config['page']['num'] = pageConfig['num']
-		return self.handle('select', type=type, col=col, order=order, group=group, limit=limit, page=pageConfig)
-
-	def manage(self):
-		self.attr(method)
-		return
-
-	def handle(self, method='select', type='fetchall', col = '*', order = '', group = '', limit = '0,100', page=False, set = ''):
-		self.attr(method)
-		if method == 'create':
-			create = self.createState()
-			if create == False:
-				return False
-		if type == 'fetchone':
-			limit = '0,1'
-		load = getattr(Sql(self._type), method)
-		return self.query(load(self._table, {'key':self._key, 'fields':self._attr, 'col':col, 'order':order, 'group':group, 'limit':limit, 'page':page, 'set':set, 'table_comment':self.__comment__}), method, type)
-
-
-class Fields(object):
-	def __init__(self, type='', default='', primaryKey=False, autoIncrement=False, null=True, unique=False, check='', constraint='', comment='', uuid='', index=False, indexs=False, md5=False, match='', manage=''):
-		self.type = type
-		self.default = default
-		self.primaryKey = primaryKey
-		self.autoIncrement = autoIncrement
-		self.null = null
-		self.unique = unique
-		self.check = check
-		self.constraint = constraint
-		self.comment = comment
-		self.uuid = uuid
-		self.index = index
-		self.indexs = indexs
-		self.md5 = md5
-		self.key = Counter().inc()
-		self.match = match
-		self.value = ''
-		self.argv = ''
-		self.bindValue = ''
-		self.expValue = '='
-		self.logicValue = 'and'
-		self.manage = manage
-
-
-	def assgin(self, value, exp='=', logic='and'):
-		self.add(value)
-		self.exp(exp)
-		self.logic(logic)
-		return self
-
-	def bind(self, value):
-		self.bindValue = value
-		return self
-
-	def exp(self, value):
-		"""
-		if type(self.expValue) != list:
-			self.expValue = []
-		self.expValue.append(value)
-		"""
-		self.expValue = value
-		return self
-
-	def logic(self, value):
-		"""
-		if type(self.logicValue) != list:
-			self.logicValue = []
-		self.logicValue.append(value)
-		"""
-		self.logicValue = value
-		return self
-
-	def val(self, value, exp='=', logic='and'):
-		if type(value) == list:
-			length = len(value)
-			if length <= 1:
-				value = value[0]
-		self.value = value
-		if not self.expValue:
-			self.exp(exp)
-		if not self.logicValue:
-			self.logic(logic)
-		return self
-
-	def getArgv(self):
-		return self.argv
-
-	def getVal(self):
-		return self.value
-
-	def getBind(self):
-		return self.bindValue
-
-	def getExp(self):
-		if not self.expValue:
-			return ''
-		if type(self.expValue) == list:
-			length = len(self.expValue)
-			if length <= 1:
-				result = self.expValue[0]
-			else:
-				result = self.expValue
-		else:
-			result = self.expValue
-		return result
-
-	def getKey(self):
-		return self.key
-
-	def getLogic(self):
-		if not self.logicValue:
-			return ''
-		if type(self.logicValue) == list:
-			length = len(self.logicValue)
-			if length <= 1:
-				result = self.logicValue[0]
-			else:
-				result = self.logicValue
-		else:
-			result = self.logicValue
-		return result
-
-	def unset(self):
-		self.argv = None
-		self.value = None
-		self.bindValue = None
-		self.expValue = '='
-		self.logicValue = 'and'
-		return self
-
-	def add(self, value):
-		"""
-		if not self.argv:
-			self.argv = []
-		self.argv.append(value)
-		"""
-		self.argv = value
-		return self
-
-	def ins(self, value):
-		self.argv = value
-		self.exp('in')
-		return self
-
-	def nq(self, value):
-		self.argv = value
-		self.exp('!=')
-		return self
-
-	def like(self, value):
-		self.argv = '%' + value + '%'
-		self.exp('like')
-		return self
-
-	def mlike(self, value):
-		self.argv = value
-		self.exp('~')
-		self.logic('and')
-		return self
-
-	def time(self, value):
-		self.add(Demeter.mktime(value))
-		return self
-
-	def start(self, value):
-		self.time(value)
-		self.exp('>=')
-		self.logic('and')
-		return self
-
-	def end(self, value):
-		self.time(value)
-		self.exp('<=')
-		self.logic('and')
-		return self
-
-class Counter(object):
-	num = 0
-	instance = None
-
-	def __new__(cls, *args, **kwd):
-		if Counter.instance is None:
-			Counter.instance = object.__new__(cls, *args, **kwd)
-		return Counter.instance
-
-	def inc(self):
-		self.num = self.num + 1
-		return self.num
-
-	def dec(self):
-		self.num = self.num - 1
-		return self.num
-
-	def unset(self):
-		self.num = 0
-		return self.num
-
-class Sql(object):
-	instance = None
-	def __new__(cls, *args, **kwd):
-		if Sql.instance is None:
-			Sql.instance = object.__new__(cls, *args, **kwd)
-		return Sql.instance
-
-	def __init__(self, type):
-		self.type = type
-
-	def drop(self, table, args):
-		sql = 'DROP TABLE IF EXISTS ' + table
-		return sql
-
-	def alter(self, table, args):
-		sql = 'ALTER TABLE ' + table + ' ADD COLUMN '
-		return sql
-
-	def create(self, table, args):
-		create = []
-		primary = []
-		unique = []
-		indexs = []
-		index = []
-		comment = {}
-		for value in args['key']:
-			key = value[0]
-			val = args['fields'][key]
-			if val.primaryKey:
-				primary.append(key)
-			if val.unique:
-				unique.append(key)
-			if val.index:
-				index.append((key, val.index))
-			if val.indexs:
-				indexs.append(key)
-
-			fields = []
-			fields.append(key)
-			if val.autoIncrement and self.type == 'postgresql':
-				fields.append('SERIAL')
-			else:
-				fields.append(val.type)
-
-			if not val.null:
-				fields.append('NOT NULL')
-				
-
-			if val.autoIncrement and self.type == 'mysql':
-				fields.append('AUTO_INCREMENT')
-
-			#约束
-			if val.constraint:
-				fields.append('CONSTRAINT ' + val.constraint)
-			if val.check:
-				fields.append('CHECK ' + val.check)
-			
-			if val.default:
-				default = val.default
-				if val.default == 'time':
-					default = '0'
-				if '.' in val.default:
-					temp = val.default.split('.')
-					default = Demeter.config[temp[0]][temp[1]]
-				fields.append('DEFAULT \'' + str(default) + '\'')
-
-			if val.comment:
-				if self.type == 'mysql':
-					fields.append('COMMENT \'' + val.comment + '\'')
-				else:
-					comment[key] = val.comment
-
-			fields = ' '.join(fields)
-			create.append(fields)
-
-		if primary:
-			create.append('PRIMARY KEY (' + ','.join(primary) + ')')
-		if unique:
-			create.append('UNIQUE (' + ','.join(unique) + ')')
-
-		create = ','.join(create)
-		sql = 'CREATE TABLE ' + table + '(' + create + ')'
-		sql = self.drop(table, args) + ';' + sql
-		if indexs:
-			name = '_'.join(indexs)
-			value = ','.join(indexs)
-			sql = sql + ';' + 'CREATE INDEX ' + table + '_' + name +' ON ' + table + '(' + value + ')'
-
-		if index:
-			for value in index:
-				sql = sql + ';' + 'CREATE INDEX ' + table + '_' + value[0] +' ON ' + table + value[1]
-
-		if comment:
-			if args['table_comment']:
-				sql = sql + ';' + 'COMMENT ON TABLE ' + table + ' IS \''+args['table_comment']+'\''
-			for key in comment:
-				sql = sql + ';' + 'COMMENT ON COLUMN ' + table + '.'+key+' IS \''+comment[key]+'\''
-		return sql
-
-	def insert(self, table, args):
-		fields = []
-		values = []
-		for value in args['key']:
-			key = value[0]
-			val = args['fields'][key].getBind()
-			if val:
-				values.append(val)
-				fields.append(key)
-
-		fields = ','.join(fields)
-		values = ','.join(values)
-		sql = 'INSERT INTO ' + table + ' (' + fields + ') VALUES (' + values + ')'
-		if self.type == 'postgresql':
-			sql = sql + ' RETURNING id'
-		return sql
-
-	def update(self, table, args):
-		fields = []
-		for key in args['set']:
-			fields.append(key + ' = %s')
-
-		fields = ','.join(fields)
-		sql = 'UPDATE ' + table + ' SET ' + fields + self.where(args['key'], args['fields'])
-		return sql
-
-	def delete(self, table, args):
-		sql = 'DELETE FROM ' + table + self.where(args['key'], args['fields'])
-		return sql
-
-	def select(self, table, args):
-		string = ' FROM ' + table + self.where(args['key'], args['fields']) + ' ' + self.group(args['group'])
-		sql = ''
-		if args['page']:
-			sql = 'SELECT count(1) as total' + string + ';'
-		sql = sql + 'SELECT ' + args['col'] + string + ' ' + self.order(args['order']) + ' ' + self.limit(args['limit'], args['page'])
-		return sql
-
-	def where(self, key, fields):
-		fields = self.fields(key, fields)
-		if fields:
-			return ' WHERE ' + fields
-		return ''
-
-	def fields(self, key, fields):
-		result = ''
-		k = 0
-		for value in key:
-			key = value[0]
-			field = fields[key]
-			bind = field.getBind()
-			val = field.getVal()
-			logic = field.getLogic()
-			exp = field.getExp()
-			if type(val) == list and val:
-				n = 0
-				for i in val:
-					data = self.field(field, bind, key, k, logic[n], exp[n])
-					n = n + 1
-					if data:
-						result = result + data
-						k = 1
-			else:
-				data = self.field(field, bind, key, k, logic, exp)
-				if data:
-					result = result + data
-					k = 1
-		return result
-
-	def field(self, field, val, key, k, logic, exp):
-		result = ''
-		if val:
-			if k == 0:
-				logic = ''
-			else:
-				logic = ' ' + logic
-			result = logic + ' ' + key + ' ' + exp + ' ' + str(val)
-		return result
-
-	def order(self, value):
-		result = ''
-		if value:
-			result = ' ORDER BY ' + value
-
-		return result
-
-	def group(self, value):
-		result = ''
-		if value:
-			result = ' GROUP BY ' + value
-
-		return result
-
-	def limit(self, value, page):
-		result = ''
-		if page:
-			value = str((int(page['current'])-1) * page['num']) + ',' + str(page['num'])
-		if value:
-			value = value.split(',')
-			if self.type == 'mysql':
-				result = ' LIMIT ' + value[0] + ',' + value[1]
-			elif self.type == 'postgresql':
-				result = ' LIMIT ' + value[1] + ' OFFSET ' + value[0]
-
-		return result

+ 0 - 102
mqtt.py

@@ -1,102 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-"""
-    demeter mqtt
-    name:connect.py
-    author:rabin
-"""
-from demeter.core import *
-import paho.mqtt.client as mqtt
-#from gevent import monkey; monkey.patch_all()
-#import gevent
-
-class Connect(object):
-
-	def __init__(self, act):
-		act.connect = self
-		self.client = mqtt.Client()
-		state = hasattr(act, 'message')
-		if state:
-			self.client.on_connect = self.connectAndSub
-			self.client.on_message = act.message
-		else:
-			self.client.on_connect = self.connect
-		self.client.connect(Demeter.config['mqtt']['host'], Demeter.config['mqtt']['port'], int(Demeter.config['mqtt']['timeout']))
-		if state:
-			self.client.loop_forever()
-
-	def __del__(self):
-		pass
-
-	def getClient(self):
-		return self.client
-
-	def connect(self, client, userdata, flags, rc):
-		pass
-
-	def connectAndSub(self, client, userdata, flags, rc):
-		#print("Connected with result code "+str(rc))
-		#client.subscribe("sensor/#")
-		sub = Demeter.config['mqtt']['sub'].split(',')
-		for value in sub:
-			client.subscribe(value + "/#")
-		"""
-		gevent.joinall([
-			gevent.spawn(self.subscribe, client, 'sensor/#'),
-			gevent.spawn(self.subscribe, client, 'pic/#'),
-			gevent.spawn(self.subscribe, client, 'msg/#'),
-		])
-		"""
-
-	@staticmethod
-	def subscribe(client, key):
-		client.subscribe(key)
-
-	def handle(self, key, value):
-		Demeter.record(key, value)
-
-
-class Pub(object):
-
-	def __init__(self):
-		Connect(self)
-
-	def __del__(self):
-		pass
-
-	def push(self, key, msg, qos=0, retain=False, callback=False, param=False, feedback=False):
-		result = self.connect.getClient().publish(key,payload=msg,qos=qos,retain=retain)
-
-		self.callback = callback
-		self.param = param
-		if feedback == True and 'key' in self.param:
-			self.connect.client.on_message = self.feedback
-			self.connect.client.subscribe(self.param['key'])
-			self.connect.client.loop_forever()
-		elif qos in (1,2):
-			self.connect.client.on_publish = self.publish
-			self.connect.client.loop_forever()
-		#else:
-			#self.connect.client.disconnect()
-		return result
-
-	def publish(self, client, userdata, mid, msg='ok'):
-		self.callback(self.param, client, userdata, mid, msg)
-		self.connect.client.disconnect()
-
-	def feedback(self, client, userdata, msg):
-		if msg.topic == self.param['key']:
-			self.publish(client, userdata, 0, msg.payload)
-
-class Sub(object):
-
-	def __init__(self):
-		Connect(self)
-
-	def __del__(self):
-		pass
-
-	def message(self, client, userdata, msg):
-		#print(msg.topic+" "+str(msg.payload))
-		#return
-		self.connect.handle(msg.topic, str(msg.payload))

+ 0 - 78
service.py

@@ -1,78 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-"""
-    demeter service
-    name:service.py 通用业务
-    author:rabin
-"""
-from demeter.core import *
-
-class Service(object):
-
-	# 获取某个model下的列表数据
-	def list(self, name, state = True, search=None, page=False, order='cdate desc', limit = '0,100'):
-		model = self.model(name)
-		model.state = state
-		if search:
-			for key, value in search.items():
-				if value or value == 0:
-					if '-' in key:
-						key = key.split('-')
-						keyLen = len(key)
-						if keyLen > 2 and key[2]:
-							method = key[2]
-						else:
-							method = 'assgin'
-						self.assgin(model, key[0], value, method)
-					else:
-						self.assgin(model, key, value)
-		data = model.select(page=page, order=order, limit=limit)
-		return data
-
-	# 获取某个model下的数据
-	def one(self, name, **kwd):
-		model = self.model(name)
-		if kwd:
-			for key,value in kwd.items():
-				self.assgin(model, key, value)
-		data = model.select(type='fetchone')
-		return data
-
-	# 更新
-	def update(self, name, id, data, cdate=True):
-		model = self.model(name)
-		if id:
-			model.id = id
-			if cdate == True and 'cdate' not in data:
-				data['cdate'] = 'time'
-			model.update(data)
-			return id
-		else:
-			for key, value in data.items():
-				method = 'assgin'
-				if 'date' in key:
-					method = 'time'
-				self.assgin(model, key, value, method)
-			return model.insert()
-
-	# 删除
-	def delete(self, name, id, state = False):
-		model = self.model(name)
-		model.id = id
-		return model.update(state=state)
-
-	# 物理删除
-	def rDelete(self, name, id):
-		model = self.model(name)
-		model.id = id
-		return model.delete()
-
-	def model(self, name):
-		return Demeter.model(name)
-
-	def assgin(self, model, key, value, method='assgin'):
-		if hasattr(model, key):
-			attr = getattr(model, key)
-			if hasattr(attr, method):
-				call = getattr(attr, method)
-				call(value)

+ 43 - 291
setup.py

@@ -1,293 +1,45 @@
 # -*- coding: utf-8 -*-
-"""
-	demeter web
-	name:application.py
-	author:rabin
-"""
-from gevent import monkey
-monkey.patch_all()
-import gevent
-import functools
-
 import os
-import json
-from demeter.core import *
-import tornado.web
-import tornado.web  
-import tornado.ioloop
-import tornado.httpserver
-import tornado.httpclient 
-import tornado.concurrent
-
-class Base(tornado.web.RequestHandler):
-	def initialize(self):
-		try:
-			Demeter.request = self
-			self.assign()
-			self.page()
-			self.cookie()
-			self.setting()
-		except Exception, e:
-			return
-
-	def get_current_user(self):
-		return self.get_secure_cookie(self.KEYS[0])
-
-	def assign(self):
-		self.data = {}
-		self.data['setting'] = Demeter.config['setting']
-		self.data['base'] = Demeter.config['base']
-		
-	def cookie(self):
-		for key in self.KEYS:
-			cookie = None
-			"""
-			if key in self.data['base']:
-				cookie = self.data['base'][key]
-			"""
-			if not cookie:
-				cookie = self.get_secure_cookie(key)
-				#cookie = self.get_cookie(key)
-			if not cookie:
-				value = self.input(key)
-				if value:
-					#self.set_secure_cookie(key, value)
-					self.data['setting'][key] = value
-				else:
-					self.data['setting'][key] = 0
-			else:
-				self.data['setting'][key] = cookie
-
-	def page(self):
-		Demeter.config['page'] = {}
-		page = self.input('page')
-		if page:
-			Demeter.config['page']['ajax'] = True
-		else:
-			Demeter.config['page']['ajax'] = False
-			page = 1
-		Demeter.config['page']['current'] = page
-		Demeter.config['page']['total'] = 0
-		self.data['page'] = Demeter.config['page']
-
-	def search(self):
-		data = self.request.arguments
-		self.data['search'] = {}
-		self.data['update'] = {}
-		for key in data:
-			if 'search_' in key:
-				index = key.replace('search_', '')
-				self.data['search'][index] = ",".join(data[key])
-			if 'update_' in key:
-				index = key.replace('update_', '')
-				self.data['update'][index] = ",".join(data[key])
-
-	def input(self, key, value=None):
-		return self.get_argument(key, value)
-
-	def inputs(self, key):
-		return self.get_arguments(key)
-
-	def service(self, name):
-		return Demeter.service(name)
-
-	def model(self, name):
-		return Demeter.model(name)
-
-	def common(self, **kwd):
-		self.data['common'] = kwd
-		self.data['common']['argvs'] = ''
-		if 'farm' in self.data['setting'] and self.data['setting']['farm'] > 0:
-			farm = str(self.data['setting']['farm'])
-			self.data['common']['argvs'] = '&farm=' + farm + '&search_farm_id-select-=' + farm
-
-	def commonView(self, name):
-		self.view('common/'+name+'.html')
-
-	def commonList(self, model, order = 'cdate desc'):
-		self.data['state'] = self.input('state', True)
-		self.data['list'] = self.service('common').list(model, state=self.data['state'], search=self.data['search'], page=True, order=order)
-
-	def commonOne(self, model, **kwd):
-		id = self.input('id')
-		self.data['info'] = {}
-		if id:
-			kwd['id'] = id
-		if kwd:
-			self.data['info'] = self.service('common').one(model, **kwd)
-		if not self.data['info'] and 'farm' in self.data['setting'] and self.data['setting']['farm'] > 0:
-			self.data['info']['farm_id'] = self.data['setting']['farm']
-
-	def commonUpdate(self, model, msg='', id=0, **kwd):
-		if not self.data['auth']:
-			self.auth()
-		else:
-			if id <= 0:
-				id = self.input('id')
-			if kwd:
-				info = self.service('common').one(model, **kwd)
-				if info and (id != info['id']):
-					self.out(msg)
-					return
-			state = self.service('common').update(model, id, self.data['update'])
-			self.log(model, 'update', self.data['update'])
-			self.out('yes', {'id':state})
-			return state
-
-	def commonDelete(self, model):
-		if not self.data['auth']:
-			self.auth()
-		else:
-			id = self.input('id')
-			state = self.input('state', False)
-			state = self.service('common').delete(model, id, state)
-			self.log(model, 'delete', {id:id, state:state})
-			self.out('yes', {'state':state})
-
-	def log(self, model, method, data):
-		if 'admin' in self.data['setting'] and self.data['setting']['admin'] > 0:
-			insert = {}
-			insert['admin_id'] = self.data['setting']['admin']
-			insert['model'] = model
-			insert['method'] = method
-			insert['data'] = json.dumps(data)
-			self.service('common').update('manage_log', None, insert)
-
-	def view(self, name):
-		if not self.data['auth']:
-			self.auth()
-		else:
-			config = Demeter.config[Demeter.web]
-			path = ''
-			if 'mobile' in config:
-				mobile = Demeter.checkMobile(self.request)
-				if mobile:
-					path = 'mobile/'
-				else:
-					path = 'pc/'
-			self.render(path + name, data=self.data, Demeter=Demeter)
-
-	def auth(self):
-		self.out('您没有权限')
-
-	def out(self, msg='', data={}, code=0):
-		if data:
-			if 'page' in data and data['page']['total'] <= 0:
-				del data['page']
-			if 'update' in data and not data['update']:
-				del data['update']
-			if 'search' in data and not data['search']:
-				del data['search']
-		callback = self.input('callback')
-		function = self.input('function')
-		result = ''
-		send = {}
-		send['status'] = 1
-		send['msg'] = msg
-		send['data'] = data
-		send['code'] = code
-		if not send['data']:
-			send['status'] = 2
-		result = json.dumps(send)
-		if callback:
-			result = callback + '(' + result + ')'
-		elif function:
-			result = '<script>parent.' + function + '(' + result + ')' + '</script>';
-		self.write(result)
-		self.finish()
-
-class Web(object):
-	@classmethod
-	def auth(self, method):
-		return tornado.web.authenticated(method)
-
-	@classmethod
-	def setting(self, method):
-		return self.async(method)
-		
-	@staticmethod
-	def async(method):
-		@tornado.web.asynchronous
-		@tornado.gen.coroutine
-		@functools.wraps(method)
-		def callback(self, *args, **kwargs):
-			#self._auto_finish = False
-			try:
-				result = method(self, *args, **kwargs)
-				return result
-			except Exception, e:
-				print e
-				return self.out('404')
-				return self.view('404.html')
-			#return gevent.spawn(method, self, *args, **kwargs)
-		return callback
-
-	@staticmethod
-	def file(path):
-		files = os.listdir(path)
-		result = []
-		for key in files:
-			if '.DS_Store' not in key and  '__' not in key and 'pyc' not in key:
-				key = key.replace('.py', '')
-				result.append(key)
-		return result
-	@staticmethod
-	def url(module, key, url):
-		str = dir(module)
-		for i in str:
-			act = ''
-			if '_path' in i:
-				act = i.replace('_path', '')
-			if '_html' in i:
-				act = i.replace('_html', '.html')
-			if act:
-				attr = getattr(module, i)
-				if key == 'main' and act == 'index':
-					url.append((r'/', attr))
-				elif key == act or act == 'index':
-					url.append((r'/'+key, attr))
-				url.append((r'/'+key+'/'+act, attr))
-		return url
-	@staticmethod
-	def start(url):
-		config = Demeter.config[Demeter.web]
-		cookie = False
-		if 'xsrf_cookies' in config:
-			cookie = Demeter.bool(config['xsrf_cookies'])
-		settings = {
-			"static_path": Demeter.webPath + 'static',
-			"template_path": Demeter.webPath + 'templates',
-			"cookie_secret": "61oETzKXQAGaYekL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=",
-			"login_url": "/user/login",
-			"xsrf_cookies": cookie,
-			"debug": Demeter.bool(config['debug']),
-			#"autoreload": Demeter.bool(config['autoreload']),
-			"port": config['port'],
-			"max_buffer_size": int(config['max_buffer_size']),
-			"process": int(config['process'])
-		}
-		handlers = []
-		def application_setting():
-			handlers.append((r"/upload/(.*)", tornado.web.StaticFileHandler, {"path": Demeter.path + 'runtime/upload/'}))
-			handlers.append((r"/qrcode/(.*)", tornado.web.StaticFileHandler, {"path": Demeter.path + 'runtime/qrcode/'}))
-			handlers.append((r"/camera/(.*)", tornado.web.StaticFileHandler, {"path": Demeter.path + 'runtime/camera/'}))
-			handlers.append((r"/static/(.*)", tornado.web.StaticFileHandler, {"path":"static"}))
-			handlers.append((r"/(apple-touch-icon\.png)", tornado.web.StaticFileHandler, dict(path=settings['static_path'])))
-			handlers.extend(url)
-
-		application_setting()
-		application = tornado.web.Application(handlers=handlers, **settings)
-		
-		if settings['debug'] == True:
-			application.listen(settings['port'])
-			tornado.ioloop.IOLoop.instance().start()
-		else:
-			server = tornado.httpserver.HTTPServer(application, settings['max_buffer_size'])
-			server.bind(settings['port'])
-			server.start(settings['process'])
-			try:		
-				print 'running on port %s' % settings['port']
-				tornado.ioloop.IOLoop.instance().start()
-
-			except KeyboardInterrupt:
-				tornado.ioloop.IOLoop.instance().stop()
+import sys
+__DIR__ = os.path.abspath(os.path.dirname(__file__))
+import codecs
+from setuptools import setup
+from setuptools.command.test import test as TestCommand
+import demeter
+
+
+def read(filename):
+    """Read and return `filename` in root dir of project and return string"""
+    return codecs.open(os.path.join(__DIR__, filename), 'r').read()
+
+
+install_requires = read("requirements.txt").split()
+long_description = read('README.md')
+
+
+setup(
+    name="Demeter",
+    version=demeter.__version__,
+    url='https://github.com/shemic/demeter',
+    license='MIT License',
+    author='Rabin',
+    description=('A simple framework based on Tornado'),
+    long_description=long_description,
+    packages=['demeter'],
+    install_requires = install_requires,
+    #tests_require=['pytest'],
+    #cmdclass = {'test': Pytest},
+    data_files=[
+        # Populate this with any files config files etc.
+    ],
+    classifiers=[
+        "Development Status :: 5 - Production/Stable",
+        "Intended Audience :: Developers",
+        "License :: OSI Approved :: MIT License",
+        "Natural Language :: English",
+        "Operating System :: OS Independent",
+        "Programming Language :: Python :: 2",
+        "Programming Language :: Python :: 3",
+        "Topic :: Software Development :: Libraries :: Application Frameworks",
+    ]
+)

+ 0 - 70
tcp.py

@@ -1,70 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-"""
-	demeter tcp
-	name:server.py
-	author:rabin
-"""
-import socket  
-import time
-from demeter.core import *
-from demeter.mqtt import *
-from tornado.tcpserver import TCPServer
-from tornado.ioloop  import IOLoop
-from tornado import stack_context  
-from tornado.escape import native_str 
-
-class Connection(object):
-	clients = set()
-	EOF = '|e|'
-	def __init__(self, stream, address):
-		Connection.clients.add(self)
-		self._pub = Pub()
-		self._stream = stream
-		self._address = address
-		self._stream.set_close_callback(self.on_close)
-		self.read_message()
-		
-	def read_message(self):
-		self._message_callback = stack_context.wrap(self.on_message)  
-		self._stream.read_until(self.EOF, self._message_callback)
-	
-	def on_message(self, data):
-		data = data.replace(self.EOF, '')
-		temp = data.split('|:|')
-		key = temp[0]
-		value = temp[1]
-		self._pub.push(key, value)
-		
-		#print "User said:", data[:-1], self._address
-		"""
-		for conn in Connection.clients:
-			conn.send_message(data)
-		"""
-		self.read_message()
-		
-	def send_message(self, data):
-		self._stream.write(data)
-			
-	def on_close(self):
-		#print "A user has left the chat room.", self._address
-		Connection.clients.remove(self)
-	
-class Server(TCPServer):	
-	def handle_stream(self, stream, address):
-		#print "New connection :", address, stream
-		Connection(stream, address)
-		#print "connection num is:", len(Connection.clients)
-
-class Client(object):
-	EOF = '|e|'
-	def __init__(self, host='0.0.0.0', port=8000):
-		self.connect = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-		self.connect.connect((host, port))
-		
-	def send(self, msg):
-		msg = msg + self.EOF
-		self.connect.sendall(msg)
-		#data = self.connect.recv(1024)
-	def close(self):
-		self.connect.close()

+ 0 - 294
web.py

@@ -1,294 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-"""
-	demeter web
-	name:application.py
-	author:rabin
-"""
-from gevent import monkey
-monkey.patch_all()
-import gevent
-import functools
-
-import os
-import json
-from demeter.core import *
-import tornado.web
-import tornado.web  
-import tornado.ioloop
-import tornado.httpserver
-import tornado.httpclient 
-import tornado.concurrent
-
-class Base(tornado.web.RequestHandler):
-	def initialize(self):
-		try:
-			Demeter.request = self
-			self.assign()
-			self.page()
-			self.cookie()
-			self.setting()
-		except Exception, e:
-			return
-
-	def get_current_user(self):
-		return self.get_secure_cookie(self.KEYS[0])
-
-	def assign(self):
-		self.data = {}
-		self.data['setting'] = Demeter.config['setting']
-		self.data['base'] = Demeter.config['base']
-		
-	def cookie(self):
-		for key in self.KEYS:
-			cookie = None
-			"""
-			if key in self.data['base']:
-				cookie = self.data['base'][key]
-			"""
-			if not cookie:
-				cookie = self.get_secure_cookie(key)
-				#cookie = self.get_cookie(key)
-			if not cookie:
-				value = self.input(key)
-				if value:
-					#self.set_secure_cookie(key, value)
-					self.data['setting'][key] = value
-				else:
-					self.data['setting'][key] = 0
-			else:
-				self.data['setting'][key] = cookie
-
-	def page(self):
-		Demeter.config['page'] = {}
-		page = self.input('page')
-		if page:
-			Demeter.config['page']['ajax'] = True
-		else:
-			Demeter.config['page']['ajax'] = False
-			page = 1
-		Demeter.config['page']['current'] = page
-		Demeter.config['page']['total'] = 0
-		self.data['page'] = Demeter.config['page']
-
-	def search(self):
-		data = self.request.arguments
-		self.data['search'] = {}
-		self.data['update'] = {}
-		for key in data:
-			if 'search_' in key:
-				index = key.replace('search_', '')
-				self.data['search'][index] = ",".join(data[key])
-			if 'update_' in key:
-				index = key.replace('update_', '')
-				self.data['update'][index] = ",".join(data[key])
-
-	def input(self, key, value=None):
-		return self.get_argument(key, value)
-
-	def inputs(self, key):
-		return self.get_arguments(key)
-
-	def service(self, name):
-		return Demeter.service(name)
-
-	def model(self, name):
-		return Demeter.model(name)
-
-	def common(self, **kwd):
-		self.data['common'] = kwd
-		self.data['common']['argvs'] = ''
-		if 'farm' in self.data['setting'] and self.data['setting']['farm'] > 0:
-			farm = str(self.data['setting']['farm'])
-			self.data['common']['argvs'] = '&farm=' + farm + '&search_farm_id-select-=' + farm
-
-	def commonView(self, name):
-		self.view('common/'+name+'.html')
-
-	def commonList(self, model, order = 'cdate desc'):
-		self.data['state'] = self.input('state', True)
-		self.data['list'] = self.service('common').list(model, state=self.data['state'], search=self.data['search'], page=True, order=order)
-
-	def commonOne(self, model, **kwd):
-		id = self.input('id')
-		self.data['info'] = {}
-		if id:
-			kwd['id'] = id
-		if kwd:
-			self.data['info'] = self.service('common').one(model, **kwd)
-		if not self.data['info'] and 'farm' in self.data['setting'] and self.data['setting']['farm'] > 0:
-			self.data['info']['farm_id'] = self.data['setting']['farm']
-
-	def commonUpdate(self, model, msg='', id=0, **kwd):
-		if not self.data['auth']:
-			self.auth()
-		else:
-			if id <= 0:
-				id = self.input('id')
-			if kwd:
-				info = self.service('common').one(model, **kwd)
-				if info and (id != info['id']):
-					self.out(msg)
-					return
-			state = self.service('common').update(model, id, self.data['update'])
-			self.log(model, 'update', self.data['update'])
-			self.out('yes', {'id':state})
-			return state
-
-	def commonDelete(self, model):
-		if not self.data['auth']:
-			self.auth()
-		else:
-			id = self.input('id')
-			state = self.input('state', False)
-			state = self.service('common').delete(model, id, state)
-			self.log(model, 'delete', {id:id, state:state})
-			self.out('yes', {'state':state})
-
-	def log(self, model, method, data):
-		if 'admin' in self.data['setting'] and self.data['setting']['admin'] > 0:
-			insert = {}
-			insert['admin_id'] = self.data['setting']['admin']
-			insert['model'] = model
-			insert['method'] = method
-			insert['data'] = json.dumps(data)
-			self.service('common').update('manage_log', None, insert)
-
-	def view(self, name):
-		if not self.data['auth']:
-			self.auth()
-		else:
-			config = Demeter.config[Demeter.web]
-			path = ''
-			if 'mobile' in config:
-				mobile = Demeter.checkMobile(self.request)
-				if mobile:
-					path = 'mobile/'
-				else:
-					path = 'pc/'
-			self.render(path + name, data=self.data, Demeter=Demeter)
-
-	def auth(self):
-		self.out('您没有权限')
-
-	def out(self, msg='', data={}, code=0):
-		if data:
-			if 'page' in data and data['page']['total'] <= 0:
-				del data['page']
-			if 'update' in data and not data['update']:
-				del data['update']
-			if 'search' in data and not data['search']:
-				del data['search']
-		callback = self.input('callback')
-		function = self.input('function')
-		result = ''
-		send = {}
-		send['status'] = 1
-		send['msg'] = msg
-		send['data'] = data
-		send['code'] = code
-		if not send['data']:
-			send['status'] = 2
-		result = json.dumps(send)
-		if callback:
-			result = callback + '(' + result + ')'
-		elif function:
-			result = '<script>parent.' + function + '(' + result + ')' + '</script>';
-		self.write(result)
-		self.finish()
-
-class Web(object):
-	@classmethod
-	def auth(self, method):
-		return tornado.web.authenticated(method)
-
-	@classmethod
-	def setting(self, method):
-		return self.async(method)
-		
-	@staticmethod
-	def async(method):
-		@tornado.web.asynchronous
-		@tornado.gen.coroutine
-		@functools.wraps(method)
-		def callback(self, *args, **kwargs):
-			#self._auto_finish = False
-			try:
-				result = method(self, *args, **kwargs)
-				return result
-			except Exception, e:
-				print e
-				return self.out('404')
-				return self.view('404.html')
-			#return gevent.spawn(method, self, *args, **kwargs)
-		return callback
-
-	@staticmethod
-	def file(path):
-		files = os.listdir(path)
-		result = []
-		for key in files:
-			if '.DS_Store' not in key and  '__' not in key and 'pyc' not in key:
-				key = key.replace('.py', '')
-				result.append(key)
-		return result
-	@staticmethod
-	def url(module, key, url):
-		str = dir(module)
-		for i in str:
-			act = ''
-			if '_path' in i:
-				act = i.replace('_path', '')
-			if '_html' in i:
-				act = i.replace('_html', '.html')
-			if act:
-				attr = getattr(module, i)
-				if key == 'main' and act == 'index':
-					url.append((r'/', attr))
-				elif key == act or act == 'index':
-					url.append((r'/'+key, attr))
-				url.append((r'/'+key+'/'+act, attr))
-		return url
-	@staticmethod
-	def start(url):
-		config = Demeter.config[Demeter.web]
-		cookie = False
-		if 'xsrf_cookies' in config:
-			cookie = Demeter.bool(config['xsrf_cookies'])
-		settings = {
-			"static_path": Demeter.webPath + 'static',
-			"template_path": Demeter.webPath + 'templates',
-			"cookie_secret": "61oETzKXQAGaYekL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=",
-			"login_url": "/user/login",
-			"xsrf_cookies": cookie,
-			"debug": Demeter.bool(config['debug']),
-			#"autoreload": Demeter.bool(config['autoreload']),
-			"port": config['port'],
-			"max_buffer_size": int(config['max_buffer_size']),
-			"process": int(config['process'])
-		}
-		handlers = []
-		def application_setting():
-			handlers.append((r"/upload/(.*)", tornado.web.StaticFileHandler, {"path": Demeter.path + 'runtime/upload/'}))
-			handlers.append((r"/qrcode/(.*)", tornado.web.StaticFileHandler, {"path": Demeter.path + 'runtime/qrcode/'}))
-			handlers.append((r"/camera/(.*)", tornado.web.StaticFileHandler, {"path": Demeter.path + 'runtime/camera/'}))
-			handlers.append((r"/static/(.*)", tornado.web.StaticFileHandler, {"path":"static"}))
-			handlers.append((r"/(apple-touch-icon\.png)", tornado.web.StaticFileHandler, dict(path=settings['static_path'])))
-			handlers.extend(url)
-
-		application_setting()
-		application = tornado.web.Application(handlers=handlers, **settings)
-		
-		if settings['debug'] == True:
-			application.listen(settings['port'])
-			tornado.ioloop.IOLoop.instance().start()
-		else:
-			server = tornado.httpserver.HTTPServer(application, settings['max_buffer_size'])
-			server.bind(settings['port'])
-			server.start(settings['process'])
-			try:		
-				print 'running on port %s' % settings['port']
-				tornado.ioloop.IOLoop.instance().start()
-
-			except KeyboardInterrupt:
-				tornado.ioloop.IOLoop.instance().stop()