forked from bmg1919/Booktype-py3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreatebooktype
More file actions
executable file
·1041 lines (796 loc) · 33.6 KB
/
Copy pathcreatebooktype
File metadata and controls
executable file
·1041 lines (796 loc) · 33.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# This file is part of Booktype.
# Copyright (c) 2012 Aleksandar Erkalovic <aleksandar.erkalovic@sourcefabric.org>
#
# Booktype is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Booktype is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Booktype. If not, see <http://www.gnu.org/licenses/>.
import sys
import os
import argparse
import string
import random
verbose = 0
def log(msg):
if verbose:
print(msg)
def logln(msg):
if verbose:
print(msg)
def show_info():
logln("Hi!\nI will use this information to create the new project:")
logln(" login: %s" % os.getlogin())
logln(" user id: %s" % os.geteuid())
logln(" group id: %s" % os.getegid())
logln("\n\n\n")
def show_after(destination, name):
logln("")
logln("Check [%s] directory for created files:" % destination)
logln(" booktype_dev.env - Environment dev variables")
logln(" booktype_stage.env - Environment stage variables")
logln(" booktype_prod.env - Environment production variables")
logln(" manage_dev.py - Manage file for dev profile")
logln(" manage_stage.py - Manage file for stage profile")
logln(" manage_prod.py - Manage file for production profile")
logln(" pytest.ini - Global py.test configuration")
logln(" conftest.py - Py.test configuration with fixtures and db pre settings")
logln(" epub2docx.sh - Pandoc convertion script from epub to docx")
logln(" epub2icml.sh - Pandoc convertion script from epub to icml")
logln(" booktype2mpdf.php - Configuration and convertion script for mpdf")
logln("")
logln(" conf/ - Configuration files")
logln(" wsgi_stage.apache - Apache config file for stage instance")
logln(" wsgi_prod.apache - Apache config file for production instance")
logln(" gunicorn_stage.nginx - Nginx config file for stage instance")
logln(" gunicorn_prod.nginx - Nginx config file for production instance")
logln(" fastcgi_stage.nginx - Nginx config file for stage instance")
logln(" fastcgi_prod.nginx - Nginx config file for production instance")
logln(" supervisor_stage.conf - Supervisor config file for stage instance")
logln(" supervisor_prod.conf - Supervisor config file for production instance")
logln("")
logln(" lib/ - Local python libraries")
logln(" static/ - Deployed static files")
logln(" data/ - Attachments, Covers, ...")
logln("")
logln(" {:<10} ".format(name + "_site")[:29] + "- Booktype project")
logln(" locale/ - Local translations")
logln(" templates/ - Local templates")
logln(" static/ - Local static files")
logln(" wsgi_dev.py - WSGI file for Apache")
logln(" wsgi_stage.py - WSGI file for Apache")
logln(" wsgi_prod.py - WSGI file for Apache")
logln("")
logln(" settings/ - Settings configurations")
logln(" base.py - Base configuration")
logln(" dev.py - Development configuration")
logln(" stage.py - Stage configuration")
logln(" prod.py - Production configuration")
logln(" test.py - Testing configuration")
logln("")
logln(" urls/ - URL routers")
logln(" dev.py - For Development profile")
logln(" stage.py - For Production profile")
logln(" prod.py - For Production profile")
logln("")
logln("For further instructions read INSTALL file.\n")
class MajorError(Exception):
def __init__(self, description=''):
self.description = description
def __str__(self):
return repr(self.description)
class InstallError(MajorError):
pass
def check_python_version():
"""Check what version of Python user has."""
major, minor = sys.version_info[:2]
if major == 2:
if minor < 7:
raise MajorError("You have old version of Python. Please upgrade.")
elif major == 2:
raise MajorError("I don't think i can work with Python 2.")
else:
logln("You should upgrade your python installation....")
def check_django_version():
"""Check what version of Django user has."""
log("+ Trying to import Django. ")
try:
import django
except ImportError:
raise InstallError()
else:
logln("[OK]")
major, minor = django.VERSION[:2]
if major == 1:
if minor < 5:
raise MajorError("You have old version of Django. Please upgrade.")
def check_booki_available():
log("+ Trying to import booktype. ")
try:
import booki
except ImportError:
raise InstallError()
else:
logln("[OK]")
def check_lxml_available():
log("+ Trying to import lxml. ")
try:
import lxml
except ImportError:
raise InstallError()
else:
logln("[OK]")
def check_pil_available():
log("+ Trying to import Python Imaging Library (PIL/Pillow). ")
try:
from PIL import Image
except ImportError:
try:
import Image
except ImportError:
raise InstallError()
else:
logln("[OK]")
else:
logln("[OK]")
def check_redis_available():
log("+ Trying to import Redis module. ")
try:
import redis
except ImportError:
raise InstallError()
else:
logln("[OK]")
def check_unidecode_available():
log("+ Trying to import Unidecode module. ")
try:
import unidecode
except ImportError:
raise InstallError()
else:
logln("[OK]")
def copy_default_themes(destination):
from shutil import copytree
try:
logln("+ Copying themes")
import booktype
booktype_source = os.path.dirname(booktype.__file__)
copytree('{}/skeleton/themes/'.format(booktype_source), '{}/themes/'.format(destination))
except OSError:
raise InstallError()
def make_directory_structure(destination):
try:
project = get_project_name(destination)
for d in ['data', 'logs', 'static', 'lib', 'conf', '%s_site' % project]:
log("+ Creating %s directory. " % d)
os.mkdir('%s/%s' % (destination, d))
logln("[OK]")
for d in ['settings', 'urls', 'templates', 'locale', 'static']:
log("+ Creating %s directory." % d)
os.mkdir('%s/%s_site/%s' % (destination, project, d))
logln("[OK]")
for d in ['books', 'profile_images', 'cover_images']:
log("+ Creating data/%s directory. " % d)
os.mkdir('%s/data/%s' % (destination, d))
logln("[OK]")
except OSError:
raise InstallError()
def read_file(file_name):
content = open(file_name, 'rt').read()
return content
def set_var(content, name, value):
return content.replace('##%s##' % name, value)
def create_mpdf(destination):
booktype_source = os.path.dirname(sys.argv[0])
try:
mpdf_content = read_file('%s/booktype2mpdf.php' % booktype_source)
except IOError:
raise MajorError("[ERROR] Can't read booktype2mpdf.php file.")
try:
log("+ Creating booktype2mpdf.php file. ")
f = open('%s/booktype2mpdf.php' % (destination, ), 'wt').write(mpdf_content)
logln("[OK]")
except IOError:
raise InstallError()
def create_pandoc(destination):
booktype_source = os.path.dirname(sys.argv[0])
# icml
try:
epub2icml_content = read_file('%s/epub2icml.sh' % booktype_source)
except IOError:
raise MajorError("[ERROR] Can't read epub2icml.sh file.")
try:
log("+ Creating epub2icml_content file. ")
open('%s/epub2icml.sh' % (destination, ), 'wt').write(epub2icml_content)
logln("[OK]")
except IOError:
raise InstallError()
# docx
try:
epub2docx_content = read_file('%s/epub2docx.sh' % booktype_source)
except IOError:
raise MajorError("[ERROR] Can't read epub2docx.sh file.")
try:
log("+ Creating epub2docx_content file. ")
open('%s/epub2docx.sh' % (destination, ), 'wt').write(epub2docx_content)
logln("[OK]")
except IOError:
raise InstallError()
def create_pytest(destination):
log("+ Creating pytest.ini file.")
import booktype
booktype_source = os.path.dirname(sys.argv[0])
booktype_path = os.path.abspath(os.path.dirname(booktype.__file__) + '/..')
project = get_project_name(destination)
try:
content = read_file('%s/pytest.ini.original' % booktype_source)
except IOError:
raise MajorError("[ERROR] Can't read pytest.ini.original file.")
content = set_var(content, "SETTINGS", "{}_site.settings.test".format(project))
content = set_var(content, "DESTINATION_PATH", destination)
content = set_var(content, "BOOKTYPE_PATH", booktype_path)
try:
log("+ Creating pytest.ini file. ")
f = open('%s/pytest.ini' % (destination,), 'wt')
f.write(content)
f.close()
logln("[OK]")
except IOError:
raise InstallError()
try:
content = read_file('%s/conftest.py' % booktype_source)
except IOError:
raise MajorError("[ERROR] Can't read conftest.py file.")
try:
log("+ Creating conftest.py file. ")
f = open('%s/conftest.py' % (destination,), 'wt')
f.write(content)
f.close()
logln("[OK]")
except IOError:
raise InstallError()
def create_urls(destination):
import booktype
booktype_source = os.path.dirname(booktype.__file__)
project = get_project_name(destination)
try:
dev_content = read_file('%s/skeleton/dev_urls.py.original' % booktype_source)
stage_content = read_file('%s/skeleton/stage_urls.py.original' % booktype_source)
prod_content = read_file('%s/skeleton/prod_urls.py.original' % booktype_source)
except IOError:
raise MajorError("[ERROR] Can't read dev_urls.py.original file.")
try:
log("+ Creating %s_site/urls/dev.py file. " % project)
f = open('%s/%s_site/urls/dev.py' % (destination, project), 'wt').write(dev_content)
logln("[OK]")
log("+ Creating %s_site/urls/stage.py file. " % project)
f = open('%s/%s_site/urls/stage.py' % (destination, project), 'wt').write(stage_content)
logln("[OK]")
log("+ Creating %s_site/urls/prod.py file. " % project)
f = open('%s/%s_site/urls/prod.py' % (destination, project), 'wt').write(prod_content)
logln("[OK]")
except IOError:
raise InstallError()
def create_settings(destination, database):
import booktype
booktype_source = os.path.dirname(booktype.__file__)
project = get_project_name(destination)
try:
log("+ Creating %s_site/__init__.py file. " % project)
open('%s/%s_site/__init__.py' % (destination, project), 'wb').close()
logln("[OK]")
log("+ Creating %s_site/settings/__init__.py file. " % project)
open('%s/%s_site/settings/__init__.py' % (destination, project), 'wb').close()
logln("[OK]")
log("+ Creating %s_site/urls/__init__.py file. " % project)
open('%s/%s_site/urls/__init__.py' % (destination, project), 'wb').close()
logln("[OK]")
except OSError:
raise InstallError()
try:
content = read_file('%s/skeleton/base_settings.py.original' % booktype_source)
dev_content = read_file('%s/skeleton/dev_settings.py.original' % booktype_source)
stage_content = read_file('%s/skeleton/stage_settings.py.original' % booktype_source)
prod_content = read_file('%s/skeleton/prod_settings.py.original' % booktype_source)
test_content = read_file('%s/skeleton/test_settings.py.original' % booktype_source)
except IOError:
raise MajorError("[ERROR] Can't read settings.py.original file.")
booktype_name = "Booktype site"
try:
secret_key = ''.join([random.SystemRandom().choice("{}{}{}".format(string.ascii_letters, string.digits, '!@#$%^&*(-_+=)')) for i in range(50)])
except NotImplementedError:
secret_key = ''.join([random.choice("{}{}{}".format(string.ascii_letters, string.digits, '!@#$%^&*(-_+=)')) for i in range(50)])
vals = {'BOOKTYPE_SITE_NAME': booktype_name,
'BOOKTYPE_SITE_DIR': '%s_site' % project,
'BOOKTYPE_ROOT': os.path.abspath(destination),
'SECRET_KEY': secret_key}
if database in ['postgresql', 'postgres']:
vals['DATABASE_ENGINE'] = 'django.db.backends.postgresql_psycopg2'
vals['DATABASE_NAME'] = ''
vals['ATOMIC_SETTING'] = ''
elif database == 'sqlite':
vals['DATABASE_ENGINE'] = 'django.db.backends.sqlite3'
vals['DATABASE_NAME'] = '%s/database.sqlite' % destination
atomic = "\n\t'ATOMIC_REQUESTS': True,"
vals['ATOMIC_SETTING'] = atomic.expandtabs(8)
for k in vals.keys():
content = set_var(content, k, vals[k])
dev_content = set_var(dev_content, k, vals[k])
stage_content = set_var(stage_content, k, vals[k])
prod_content = set_var(prod_content, k, vals[k])
test_content = set_var(test_content, k, vals[k])
try:
log("+ Creating %s_site/settings/base.py file. " % project)
open('%s/%s_site/settings/base.py' % (destination, project), 'wt').write(content)
logln("[OK]")
log("+ Creating %s_site/settings/dev.py file. " % project)
open('%s/%s_site/settings/dev.py' % (destination, project), 'wt').write(dev_content)
logln("[OK]")
log("+ Creating %s_site/settings/stage.py file. " % project)
open('%s/%s_site/settings/stage.py' % (destination, project), 'wt').write(stage_content)
logln("[OK]")
log("+ Creating %s_site/settings/prod.py file. " % project)
open('%s/%s_site/settings/prod.py' % (destination, project), 'wt').write(prod_content)
logln("[OK]")
log("+ Creating %s_site/settings/prod.py file. " % project)
open('%s/%s_site/settings/test.py' % (destination, project), 'wt').write(test_content)
logln("[OK]")
except IOError:
raise InstallError()
def get_project_name(destination):
dirs = [n for n in os.path.abspath(destination).split(os.sep) if n.strip() != '']
return dirs[-1]
def get_project_directory(destination):
dirs = [n for n in os.path.abspath(destination).split(os.sep) if n.strip() != '']
return os.sep.join(dirs[:-1])
def create_manage(destination, profile):
log("+ Creating manage_{}.py file.".format(profile))
import booktype
import stat
booktype_source = os.path.dirname(booktype.__file__)
booktype_path = os.path.abspath(os.path.dirname(booktype.__file__) + '/..')
project = get_project_name(destination)
try:
content = read_file('%s/skeleton/manage_{}.py.original'.format(profile) % booktype_source)
except IOError:
raise MajorError("[ERROR] Can't read manage_{}.py.original file.".format(profile))
content = set_var(content, "SETTINGS", "{}_site.settings.{}".format(project, profile))
content = set_var(content, "DESTINATION_PATH", destination)
content = set_var(content, "BOOKTYPE_PATH", booktype_path)
try:
log("+ Creating manage_{}.py file. ".format(profile))
f = open('{}/manage_{}.py'.format(destination, profile), 'wt')
f.write(content)
# Set execute flag
s = stat.S_IRWXU | stat.S_IWUSR | stat.S_IXUSR
s = s | stat.S_IRGRP
s = s | stat.S_IROTH
os.fchmod(f.fileno(), s)
f.close()
logln("[OK]")
except IOError:
raise InstallError()
def create_env(destination, profile):
log("+ Creating booktype_{}.env file. ".format(profile))
import booki
booki_path = os.path.abspath(os.path.dirname(booki.__file__) + '/..')
try:
f = open('{}/booktype_{}.env'.format(destination, profile), 'wt')
f.write('''# Booktype comes with predefined settings:
# %(project_name)s_site.settings.dev [for development]
# %(project_name)s_site.settings.stage [for stage instance]
# %(project_name)s_site.settings.prod [for production instance]
export DJANGO_SETTINGS_MODULE=%(project_name)s_site.settings.%(profile)s
# If your libraries are in non standard place, you should add path to them here.
export PYTHONPATH=$PYTHONPATH:%(destination)s/:%(destination)s/lib/:%(booktype_path)s
# If your libraries/apps are in non standard place, you should add path to them here.
# e.g.
# PATH=$PATH:/Users/mirko/bin/
export PYTHONPATH PATH
''' % {'project_name': get_project_name(destination),
'location': get_project_directory(destination),
'destination': destination,
'profile': profile,
'booktype_path': booki_path})
f.close()
except OSError:
raise InstallError()
else:
logln("[OK]")
def create_wsgi(destination, profile, virtual_env):
log("+ Creating booktype.wsgi_{} file. ".format(profile))
import booki
booki_path = os.path.abspath(os.path.dirname(booki.__file__) + '/..')
try:
f = open('%s/%s_site/wsgi_%s.py' % (destination, get_project_name(destination), profile), 'wt')
f.write('''"""
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also
might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI
middleware here, or combine a Django application with an application of another
framework.
"""
import os
import sys
# EDIT THIS VALUE
# VIRTUAL_PATH='%(virtual_env)s'
# if VIRTUAL_PATH != '':
# activate_this = '{}/bin/activate'.format(VIRTUAL_PATH)
# # execfile(activate_this, dict(__file__=activate_this))
# exec(open(activate_this).read())
from pathlib import Path
BASE_DIR = Path(os.path.abspath(__file__)).parent.parent
sys.path.insert(0, str(BASE_DIR))
sys.path.insert(0, str(BASE_DIR / "lib"))
sys.path.insert(0, '%(booki_path)s/')
# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks
# if running multiple sites in the same mod_wsgi process. To fix this, use
# mod_wsgi daemon mode with each site in its own daemon process, or use
os.environ["DJANGO_SETTINGS_MODULE"] = "%(project_name)s_site.settings.%(profile)s"
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
''' % {'directory': get_project_directory(destination),
'destination': destination,
'booki_path': booki_path,
'profile': profile,
'virtual_env': virtual_env,
'project_name': get_project_name(destination)})
f.close()
except OSError:
raise InstallError()
else:
logln("[OK]")
def include_celery(destination):
log("+ Import celery in {}_site __init__ file".format(get_project_name(destination)))
try:
f = open('%s/%s_site/__init__.py' % (destination, get_project_name(destination)), 'wt')
f.write('''
from __future__ import absolute_import, unicode_literals
# TODO we should have ability to change profile mode for celery
# in general we need ENV-variables driven settings, but it will require bigger changes
from .celery import app as celery_app
__all__ = ['celery_app']
''')
f.close()
except OSError:
raise InstallError()
else:
logln("[OK]")
def create_celery(destination):
log("{} + Creating celery.py file. ".format(profile))
import booki
booki_path = os.path.abspath(os.path.dirname(booki.__file__) + '/..')
try:
f = open('%s/%s_site/celery.py' % (destination, get_project_name(destination)), 'wt')
f.write('''
from __future__ import absolute_import, unicode_literals
import os
import sys
from pathlib import Path
from celery import Celery
BASE_DIR = Path(os.path.abspath(__file__)).parent.parent
sys.path.insert(0, str(BASE_DIR))
sys.path.insert(0, str(BASE_DIR / "lib"))
sys.path.insert(0, '{booki_path}')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', '{project_name}_site.settings.dev')
app = Celery('celery_booktype')
# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
# should have a `CELERY_` prefix.
app.config_from_object('django.conf:settings', namespace='CELERY')
# Load task modules from all registered Django app configs.
app.autodiscover_tasks()
'''.format(booki_path=booki_path, project_name=get_project_name(destination)))
f.close()
except OSError:
raise InstallError()
else:
logln("[OK]")
def create_supervisor(destination, profile, virtual_env):
log("+ Creating supervisor_{}.conf file.".format(profile))
s = '''[program:%(project_name)s-celery-worker]
directory = %(project_directory)s
command = %(virtualenv)s/bin/python -m celery worker --app=%(project_name)s_site --concurrency=20
user = www-data
stopwaitsecs = 60
''' % {
'project_name': get_project_name(destination),
'virtualenv': virtual_env,
'project_directory': destination,
'profile': profile
}
try:
f = open('%s/conf/supervisor_%s.conf' % (destination, profile), 'wt')
f.write(s)
f.close()
except OSError:
raise InstallError()
else:
logln("[OK]")
def create_apache(destination, profile):
log("+ Creating wsgi_{}.apache file. ".format(profile))
import booki
booki_source = os.path.dirname(booki.__file__)
try:
import django
django_path = os.path.dirname(django.__file__)
except ImportError:
django_path = ''
s = '''# Apache configuration for Booktype Server
<VirtualHost *:80>
# Change the following three lines for your server
ServerName __INSERT_SERVER_NAME__
SetEnv HTTP_HOST "__INSERT_SERVER_NAME__"
ServerAdmin __INSERT_ADMIN_EMAIL__
SetEnv LC_TIME "en_GB.UTF-8"
SetEnv LANG "en_GB.UTF-8"
WSGIScriptAlias / %(destination)s/%(project_name)s_site/wsgi_%(profile)s.py
# Comment next 2 lines if using older Apache than v2.4
WSGIDaemonProcess %(project_name)s_wsgi python-path="__PATH_TO_ENV_SITE-PACKAGES_FOLDER__"
WSGIProcessGroup %(project_name)s_wsgi
# Comment 'Require all granted' for older Apache than v2.4
<Location "/">
Require all granted
Options FollowSymLinks
</Location>
Alias /static/ "%(destination)s/static/"
<Directory "%(destination)s/static/">
Require all granted
Options -Indexes
</Directory>
Alias /data/ "%(destination)s/data/"
<Directory "%(destination)s/data/">
Require all granted
Options -Indexes
</Directory>
ErrorLog ${APACHE_LOG_DIR}/booktype-%(project_name)s-error.log
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/booktype-%(project_name)s-access.log combined
</VirtualHost>''' % {
'destination': destination,
'booki_source': booki_source,
'project_name': get_project_name(destination),
'django_path': django_path,
'profile': profile
}
try:
f = open('%s/conf/wsgi_%s.apache' % (destination, profile), 'wt')
f.write(s)
f.close()
except OSError:
raise InstallError()
else:
logln("[OK]")
def create_nginx_gunicorn(destination, profile):
log("+ Creating gunicorn_{}.nginx file. ".format(profile))
import booki
booki_source = os.path.dirname(booki.__file__)
try:
import django
django_path = os.path.dirname(django.__file__)
except ImportError:
django_path = ''
s = '''# Nginx configuration file for gunicorn v1.0
# This configuration assumes you are using Gunicorn (http://gunicorn.org/)
# to run your Booktype installation on port 8000
server {
# We assume you are running your web server on port 80
listen 80;
# You should insert your server name here. For instance: booktype.myserver.com
server_name __INSERT_SERVER_NAME__;
# Path to the log files
access_log /var/log/nginx/booktype_access.log;
error_log /var/log/nginx/booktype_error.log;
location /static/ {
alias %(destination)s/static/;
if ($query_string) {
expires max;
}
}
location /data/ {
alias %(destination)s/data/;
if ($query_string) {
expires max;
}
}
location / {
proxy_pass_header Server;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Scheme $scheme;
proxy_connect_timeout 10;
proxy_read_timeout 10;
proxy_pass http://localhost:8000/;
}
}''' % {
'destination': destination,
'booki_source': booki_source,
'django_path': django_path
}
try:
f = open('%s/conf/gunicorn_%s.nginx' % (destination, profile), 'wt')
f.write(s)
f.close()
except OSError:
raise InstallError()
else:
logln("[OK]")
def create_nginx_fastcgi(destination, profile):
log("+ Creating factcgi_{}.nginx file. ".format(profile))
import booki
booki_source = os.path.dirname(booki.__file__)
try:
import django
django_path = os.path.dirname(django.__file__)
except ImportError:
django_path = ''
s = '''# Nginx configuration file for fastcgi v1.0
# This configuration assumes you are using fastcgi
# to run your Booktype installation on port 8000
server {
# We assume you are running your web server on port 80
listen 80;
# You should insert your server name here. For instance: booktype.myserver.com
server_name __INSERT_SERVER_NAME__;
# Path to the log files
access_log /var/log/nginx/booktype_access.log;
error_log /var/log/nginx/booktype_error.log;
location /static/ {
alias %(destination)s/static/;
if ($query_string) {
expires max;
}
}
location /data/ {
alias %(destination)s/data/;
if ($query_string) {
False expires max;
}
}
location / {
# host and port to fastcgi server
fastcgi_pass 127.0.0.1:8000;
fastcgi_param PATH_INFO $fastcgi_script_name;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param QUERY_STRING $query_string;
fastcgi_param CONTENT_TYPE $content_type;
fastcgi_param CONTENT_LENGTH $content_length;
fastcgi_pass_header Authorization;
fastcgi_intercept_errors off;
}
}''' % {'destination': destination,
'booki_source': booki_source,
'django_path': django_path}
try:
f = open('%s/conf/fastcgi_%s.nginx' % (destination, profile), 'wt')
f.write(s)
f.close()
except OSError:
raise InstallError()
else:
logln("[OK]")
if __name__ == '__main__':
PROFILES = ('dev', 'stage', 'prod')
parser = argparse.ArgumentParser(description='Create Booktype project')
parser.add_argument("-q", "--quiet", help="Do not display output messages",
action="store_true", default=False)
parser.add_argument("-v", "--verbose", help="Increase output verbosity",
action="store_true", default=True)
parser.add_argument("-d", "--database", choices=["postgresql", "postgres", "sqlite"],
help="Database backend", default="postgresql")
parser.add_argument("-c", "--check-versions", help="Check versions of packages",
action="store_true", default=True, dest="check_versions")
parser.add_argument("--virtual-env", help="specifies the default VIRTUAL_ENV",
default=os.environ.get('VIRTUAL_ENV', ''))
parser.add_argument("project", help="Path to Booktype project")
args = parser.parse_args()
verbose = args.verbose
if args.quiet:
verbose = False
project_destination = os.path.abspath(args.project)
sys.path.insert(0, os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), os.pardir, os.pardir, 'lib')))
try:
project_name = get_project_name(project_destination)
if project_name.lower() in ['booktype', 'booki', 'objavi']:
raise MajorError("Not a valid project name")
if ' ' in project_name:
raise MajorError("Space not allowed in project name")
if '-' in project_name:
raise MajorError("Minus not allowed in project name. Try to use '_' instead.")
# if args.virtual_env:
# activate_this = '{}/bin/activate'.format(args.virtual_env)
# # execfile(activate_this, dict(__file__=activate_this))
# exec(open(activate_this, 'rb').read())
# check versions of software
if args.check_versions:
check_python_version()
check_django_version()
check_booki_available()
check_lxml_available()
check_pil_available()
check_redis_available()
check_unidecode_available()
# show info about user id, group id and etc...
# show_info()
# check if project directory exists
if os.path.exists(project_destination):
if os.access(project_destination, os.W_OK):
if os.path.exists('%s/%s_site/settings/base.py' % (project_destination, get_project_name(project_destination))):
raise MajorError("\nBooktype project does exist [%s]. I don't know what to do now. Choose another directory or manualy fix issues. Sorry about that.\n" % project_destination)
else:
while True:
proceed_anyway = input("\nProject directory does exist [%s]. Directory might be already created by administrator and you just need to populate it with booktype project files...\n * If that is the case, type 'yes'.\n * If you are not sure, type 'no'.\nProceed anyway [yes/no] ? : " % project_destination)
if proceed_anyway.strip().lower() == 'no':
sys.exit(-1)
elif proceed_anyway.strip().lower() == 'yes':
break
else:
raise MajorError("Project directory exists [%s]. Can't write to this directory! Check your permissions before we continue." % project_destination)
else:
try:
os.mkdir(project_destination)
except OSError:
raise MajorError("Can't create directory [%s]. Check your permissions before we continue." % project_destination)
# create directory structure
make_directory_structure(project_destination)
# create environment variables
for profile in PROFILES:
create_env(project_destination, profile)
# create manage_*.py file
for profile in PROFILES:
create_manage(project_destination, profile)
# create settings_*.py file
create_settings(project_destination, database=args.database)
# create booktype2mpdf.php file
create_mpdf(project_destination)
# create pandoc shell script files
create_pandoc(project_destination)