PageRenderTime 54ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 1ms

/start_app.py

https://bitbucket.org/finalbattle/torweb
Python | 309 lines | 300 code | 4 blank | 5 comment | 0 complexity | b013944648e03955f8ea76f14d2de148 MD5 | raw file
  1. ############################################
  2. #!/usr/bin/env python
  3. #
  4. # -*- coding: utf-8 -*-
  5. # created: zhangpeng <zhangpeng@ivtime.com>
  6. import os
  7. import sys
  8. from os.path import abspath, dirname
  9. MYSQL_ROOT_USER = "root"
  10. MYSQL_ROOT_PASS = "1"
  11. start_path = abspath(dirname(__file__))
  12. init_text = '''#!/usr/bin/python
  13. # -*- coding: utf-8 -*-
  14. # created by start_app
  15. from os.path import abspath, dirname, join
  16. base_path = abspath(dirname(__file__))
  17. # 添加系统路径
  18. import sys
  19. sys.path.insert(0, abspath(join(base_path, '..', 'lib')))
  20. from torweb.config import Yaml_Config
  21. Yaml_Config(join(base_path, 'settings.yaml'))
  22. '''
  23. handler_text = '''#!/usr/bin/env python
  24. # -*- coding: utf-8 -*-
  25. # created by start_app
  26. from torweb.handlers import BaseHandler
  27. from %(app)s.shortcuts import *
  28. from code import interact
  29. class Handler(BaseHandler):
  30. def on_finish(self):
  31. from %(app)s import session
  32. session.remove()
  33. #print 'session removed'
  34. def render(self, template, **kwargs):
  35. tmpl = env.get_template(template)
  36. self.write(tmpl.render(**kwargs))
  37. '''
  38. shortcuts_text = '''#!/usr/bin/env python
  39. # -*- coding: utf-8 -*-
  40. # created by start_app
  41. from torweb.urls import url
  42. from torweb.handlers import *
  43. from code import interact
  44. from %(app)s import *
  45. #cache.clear()
  46. from storm.locals import *
  47. from storm.expr import Sum,LeftJoin,Eq,Or,And,Func
  48. from storm.tracer import debug as storm_debug
  49. from sqlalchemy import Table
  50. from sqlalchemy.orm import mapper
  51. from sqlalchemy import select, and_, or_
  52. from sqlalchemy.ext.declarative import declarative_base
  53. Base = declarative_base()
  54. # 设置模板目录
  55. from torweb.tmpl import FragmentCacheExtension
  56. debug = True
  57. from jinja2 import Environment, PackageLoader, MemcachedBytecodeCache, FileSystemBytecodeCache
  58. env = Environment(
  59. loader = PackageLoader('%(app)s', 'templates'),
  60. auto_reload = debug,
  61. extensions = [FragmentCacheExtension],
  62. bytecode_cache = MemcachedBytecodeCache(cache, prefix="%(app)s/jinja2/bytecode/", timeout=3600*24*8)
  63. )
  64. env.fragment_cache = cache
  65. '''
  66. settings_text = '''app: %(app)s
  67. language: python
  68. static_dir: static
  69. static_url: /static/
  70. static_domain: /static
  71. #static_domain: http://static.%(app)s.com
  72. schemes:
  73. - scheme: mysql
  74. user: %(MYSQL_ROOT_USER)s
  75. pass: %(MYSQL_ROOT_PASS)s
  76. host: 127.0.0.1
  77. port: 3306
  78. db: %(app)s
  79. storm: store
  80. sqlalchemy: session
  81. memcached: ['127.0.0.1:11211']
  82. ############################################
  83. # SessionStore
  84. # MemcachedSessionStore
  85. ############################################
  86. session_store: MemcachedSessionStore
  87. '''
  88. test_models_text = '''#!/usr/bin/env python
  89. # -*- coding: utf-8 -*-
  90. # created by start_app
  91. from %(app)s.shortcuts import *
  92. from torweb.db import CacheQuery
  93. # sqlalchemy
  94. test_model = Table('test_model', metadata, schema='%(app)s', autoload=True)
  95. class Test_Model_Base(Base):
  96. __table__ = test_model
  97. __mapper_args__ = {
  98. 'column_prefix':'_'
  99. }
  100. @classmethod
  101. def query(cls):
  102. return CacheQuery(cls)
  103. def get_name(self):
  104. return self._name
  105. def get_email(self):
  106. return self._email
  107. def __repr__(self):
  108. return u'<test_model '+self._name+'>'
  109. def __unicode__(self):
  110. return self.__repr__()
  111. # storm
  112. class Test_Model(Test_Model_Base):
  113. __storm_table__ = 'test_model'
  114. id = Int(primary=True)
  115. name = Unicode(default=u'')
  116. email = Unicode(default=u'')
  117. '''
  118. test_views_text = '''#!/usr/bin/env python
  119. # -*- coding: utf-8 -*-
  120. # created by start_app
  121. from tornado.web import addslash
  122. from torweb.urls import url
  123. from torweb.handlers import BaseHandler
  124. from %(app)s.handlers import Handler
  125. from code import interact
  126. @url(r'/')
  127. class Index(Handler):
  128. def get(self):
  129. self.render('index.html')
  130. @url(r'/test/')
  131. class MyIndex(BaseHandler):
  132. def get(self, *args, **kwargs):
  133. self.write('application is running ...')
  134. '''
  135. dev_server_text = '''
  136. # -*- coding: utf-8 -*-
  137. import %(app)s
  138. import tornado.web
  139. import tornado.options
  140. from torweb import run_torweb
  141. from torweb import make_application
  142. from optparse import OptionParser
  143. from code import interact
  144. if __name__ == '__main__':
  145. debug = True
  146. usage = "usage: %prog [options] arg1"
  147. default_port = 8888
  148. options = OptionParser(usage)
  149. options.add_option("-p", "--port", dest="port", default=default_port,
  150. help="server listenning port, default is %d" % default_port,
  151. metavar="PORT")
  152. (option, args) = options.parse_args()
  153. if debug:
  154. tornado.options.parse_command_line(args)
  155. app = make_application(payment, debug, wsgi=False)
  156. run_torweb.run(app, port=option.port)
  157. '''
  158. command_text = '''
  159. # -*- coding: utf-8 -*-
  160. # created: zhangpeng <zhangpeng@ivtime.com>
  161. import %(app)s
  162. from torweb.command import Command
  163. from code import interact
  164. if __name__ == '__main__':
  165. command = Command(payment)
  166. command.run()
  167. '''
  168. test_sql_text = '''--
  169. -- Table structure for table `user_info`
  170. --
  171. DROP TABLE IF EXISTS `user_info`;
  172. /*!40101 SET @saved_cs_client = @@character_set_client */;
  173. /*!40101 SET character_set_client = utf8 */;
  174. CREATE TABLE `user_info` (
  175. `id` int(11) NOT NULL AUTO_INCREMENT,
  176. `name` varchar(255) DEFAULT '',
  177. `email` varchar(255) DEFAULT '',
  178. PRIMARY KEY (`id`)
  179. ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
  180. /*!40101 SET character_set_client = @saved_cs_client */;
  181. --
  182. -- Dumping data for table `user_info`
  183. --
  184. LOCK TABLES `user_info` WRITE;
  185. /*!40000 ALTER TABLE `user_info` DISABLE KEYS */;
  186. /*!40000 ALTER TABLE `user_info` ENABLE KEYS */;
  187. UNLOCK TABLES;
  188. '''
  189. def start_app(app):
  190. app_path = os.path.join(start_path, app)
  191. app_init_file = os.path.join(start_path, app, '__init__.py')
  192. app_handlers_file = os.path.join(start_path, app, 'handlers.py')
  193. app_shortcuts_file = os.path.join(start_path, app, 'shortcuts.py')
  194. app_settings_file = os.path.join(start_path, app, 'settings.yaml')
  195. app_models_path = os.path.join(start_path, app, 'models')
  196. app_models_init_file = os.path.join(start_path, app, 'models', '__init__.py')
  197. app_models_test_file = os.path.join(start_path, app, 'models', 'test.py')
  198. app_views_path = os.path.join(start_path, app, 'views')
  199. app_views_init_file = os.path.join(start_path, app, 'views', '__init__.py')
  200. app_views_test_file = os.path.join(start_path, app, 'views', 'test.py')
  201. #app_test_sql = os.path.join(start_path, app, 'test.sql')
  202. dev_server_file = os.path.join(start_path, "dev_server.py")
  203. command_file = os.path.join(start_path, "command.py")
  204. if not os.path.exists(app_path):os.makedirs(app_path)
  205. if not os.path.exists(app_init_file):
  206. with open(app_init_file, 'w') as file:
  207. file.write(init_text)
  208. file.close()
  209. if not os.path.exists(app_handlers_file):
  210. with open(app_handlers_file, 'w') as file:
  211. file.write(handler_text % {'app':app})
  212. file.close()
  213. if not os.path.exists(app_shortcuts_file):
  214. with open(app_shortcuts_file, 'w') as file:
  215. file.write(shortcuts_text % {'app':app})
  216. file.close()
  217. if not os.path.exists(app_settings_file):
  218. with open(app_settings_file, 'w') as file:
  219. file.write(settings_text % {'app':app, 'MYSQL_ROOT_USER':MYSQL_ROOT_USER, 'MYSQL_ROOT_PASS':MYSQL_ROOT_PASS})
  220. file.close()
  221. if not os.path.exists(app_models_path):os.makedirs(app_models_path)
  222. if not os.path.exists(app_models_init_file):
  223. with open(app_models_init_file, 'w') as file:
  224. file.write('')
  225. file.close()
  226. if not os.path.exists(app_models_test_file):
  227. with open(app_models_test_file, 'w') as file:
  228. file.write(test_models_text % {'app':app, 's':'s'})
  229. file.close()
  230. if not os.path.exists(app_views_path):os.makedirs(app_views_path)
  231. if not os.path.exists(app_views_init_file):
  232. with open(app_views_init_file, 'w') as file:
  233. file.write('')
  234. file.close()
  235. if not os.path.exists(app_views_test_file):
  236. with open(app_views_test_file, 'w') as file:
  237. file.write(test_views_text % {'app':app})
  238. file.close()
  239. #if not os.path.exists(app_test_sql):
  240. # with open(app_test_sql, 'w') as file:
  241. # file.write(test_sql_text)
  242. # file.close()
  243. if not os.path.exists(dev_server_file):
  244. with open(dev_server_file, 'w') as file:
  245. file.write(dev_server_text % {"app": app})
  246. file.close()
  247. if not os.path.exists(command_file):
  248. with open(command_file, 'w') as file:
  249. file.write(command_text % {"app": app})
  250. file.close()
  251. import os
  252. #def start_db(app):
  253. # #cmd = "mysqladmin -u %(MYSQL_ROOT_USER)s -p%(MYSQL_ROOT_PASS)s create %(app)s" % {'app':app, 'MYSQL_ROOT_USER':MYSQL_ROOT_USER, 'MYSQL_ROOT_PASS':MYSQL_ROOT_PASS}
  254. # #os.system(cmd)
  255. # #load_cmd = "mysql -u %(MYSQL_ROOT_USER)s -p%(MYSQL_ROOT_PASS)s %(app)s < %(app)s/test.sql" % {'app':app, 'MYSQL_ROOT_USER':MYSQL_ROOT_USER, 'MYSQL_ROOT_PASS':MYSQL_ROOT_PASS}
  256. # os.system(load_cmd)
  257. if __name__ == '__main__':
  258. try:
  259. if sys.argv[1]:
  260. start_app(sys.argv[1])
  261. #start_db(sys.argv[1])
  262. print sys.argv[1]
  263. except IndexError:
  264. print u'请输入app名字'