index
int64
repo_name
string
branch_name
string
path
string
content
string
import_graph
string
69,897
Cho1s/Site1
refs/heads/master
/taskmanager/main/migrations/0003_auto_20210901_2023.py
# Generated by Django 3.2.6 on 2021-09-01 17:23 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('main', '0002_auto_20210901_2019'), ] operations = [ migrations.AddField( model_name='categorie', name='slug', field=models.SlugField(default=django.utils.timezone.now, max_length=25, verbose_name='URL'), preserve_default=False, ), migrations.AddField( model_name='portfolio', name='slug', field=models.SlugField(default=django.utils.timezone.now, max_length=25, verbose_name='URL'), preserve_default=False, ), ]
{"/taskmanager/main/views.py": ["/taskmanager/main/models.py"], "/taskmanager/main/admin.py": ["/taskmanager/main/models.py"]}
69,898
Cho1s/Site1
refs/heads/master
/taskmanager/main/views.py
from django.shortcuts import render from .models import * # Create your views here. def index(request): categorie = Categorie.objects.all() portfolio = Portfolio.objects.all() menu = { 'ОБО МНЕ': 'about', 'ВИДЫ': 'type', 'МОИ РАБОТЫ': 'portfolio', 'ВИДЕО': 'video', 'КОНТАКТ': 'contact' } data = { 'categorie': categorie, 'portfolio': portfolio, 'menu': menu } return render(request, 'main/index.html', data)
{"/taskmanager/main/views.py": ["/taskmanager/main/models.py"], "/taskmanager/main/admin.py": ["/taskmanager/main/models.py"]}
69,899
Cho1s/Site1
refs/heads/master
/taskmanager/main/admin.py
from django.contrib import admin from .models import * # Register your models here. class PortfolioAdmin(admin.ModelAdmin): list_display = ['title', 'cat'] prepopulated_fields = {'slug': ('title',)} class CategorieAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('name',)} admin.site.register(Portfolio, PortfolioAdmin) admin.site.register(Categorie, CategorieAdmin)
{"/taskmanager/main/views.py": ["/taskmanager/main/models.py"], "/taskmanager/main/admin.py": ["/taskmanager/main/models.py"]}
69,900
Cho1s/Site1
refs/heads/master
/taskmanager/main/migrations/0001_initial.py
# Generated by Django 3.2.6 on 2021-08-29 12:50 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Barbecue', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=20, verbose_name='Название')), ('price', models.IntegerField(verbose_name='Цена')), ('description', models.TextField(verbose_name='Описание')), ], options={ 'verbose_name': 'Барбекю', 'verbose_name_plural': 'Барбекюс', }, ), migrations.CreateModel( name='Categorie', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=20, verbose_name='Категория')), ], ), migrations.CreateModel( name='Fireplace', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=20, verbose_name='Название')), ('price', models.IntegerField(verbose_name='Цена')), ('description', models.TextField(verbose_name='Описание')), ], options={ 'verbose_name': 'Камин', 'verbose_name_plural': 'Камины', }, ), migrations.CreateModel( name='Stove', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=20, verbose_name='Название')), ('price', models.IntegerField(verbose_name='Цена')), ('description', models.TextField(verbose_name='Описание')), ], options={ 'verbose_name': 'Печка', 'verbose_name_plural': 'Печки', }, ), migrations.CreateModel( name='Portfolio', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('small_image', models.ImageField(upload_to='static/img/portfolio')), ('large_image', models.ImageField(upload_to='static/img/portfolio')), ('title', models.CharField(max_length=20)), ('cat', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='main.categorie', verbose_name='Категория')), ], ), ]
{"/taskmanager/main/views.py": ["/taskmanager/main/models.py"], "/taskmanager/main/admin.py": ["/taskmanager/main/models.py"]}
69,901
Cho1s/Site1
refs/heads/master
/taskmanager/main/models.py
from django.db import models # Create your models here. class Categorie(models.Model): name = models.CharField('Категория', max_length=20) slug = models.SlugField(max_length=25, verbose_name='URL') description = models.TextField('Описание', max_length=100) def __str__(self): return self.name class Portfolio(models.Model): small_image = models.ImageField(upload_to='static/img/portfolio') large_image = models.ImageField(upload_to='static/img/portfolio') title = models.CharField(max_length=20) slug = models.SlugField(max_length=25, verbose_name='URL') cat = models.ForeignKey('Categorie', on_delete=models.CASCADE, verbose_name='Категория') def __str__(self): return self.title
{"/taskmanager/main/views.py": ["/taskmanager/main/models.py"], "/taskmanager/main/admin.py": ["/taskmanager/main/models.py"]}
69,902
Cho1s/Site1
refs/heads/master
/taskmanager/main/migrations/0002_auto_20210901_2019.py
# Generated by Django 3.2.6 on 2021-09-01 17:19 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('main', '0001_initial'), ] operations = [ migrations.DeleteModel( name='Barbecue', ), migrations.DeleteModel( name='Fireplace', ), migrations.DeleteModel( name='Stove', ), ]
{"/taskmanager/main/views.py": ["/taskmanager/main/models.py"], "/taskmanager/main/admin.py": ["/taskmanager/main/models.py"]}
69,903
EungSeon/project
refs/heads/master
/project#10.py
def expressions(num): answer = 1 # 모든 숫자는 최소 1가지 방법이 존재 sum = 0 start = 0 while start != (num // 2 + 1): # 시작점은 절반(num//2)이면 충분하다. if sum < num: for i in range(start+1, num // 2 + 1 + 1): sum += i if sum == num: # num과 같으면 answer += 1 # 경우의 수를 하나 찾았으므로 1 증가 start += 1 # 시작점 1 증가 sum = 0 # sum을 0으로 초기화 break elif sum > num: # num을 초과하면 start += 1 # 시작점 1 증가 sum = 0 # sum을 0으로 초기화 break return answer # 아래는 테스트로 출력해 보기 위한 코드입니다. print(expressions(15));
{"/project.py": ["/input1.py", "/process.py", "/output.py"]}
69,904
EungSeon/project
refs/heads/master
/project#9.py
import plotly plotly.tools.set_credentials_file(username='eungseon', api_key='ntzaOnpFsaTSJRRVYJPr') import plotly.plotly as py import plotly.graph_objs as go stream_id = '6b14yummvl' stream_1 = dict(token=stream_id, maxpoints=60) trace1 = go.Scatter( x=[], y=[], mode='lines+markers', stream=stream_1 ) data = go.Data([trace1]) layout = go.Layout(title='Time Series') fig = go.Figure(data=data, layout=layout) py.plot(fig, filename='python-streaming') s = py.Stream(stream_id) s.open() import datetime import time import random import math time.sleep(5) degree = 10 temp = 10 while True: th = math.radians(degree) # 각도를 theta(radian값)으로 변환 k = math.radians(temp) sin_value = math.sin(th) y = k * sin_value # x축은 degree(각도), y축은 함수 y = ksinx 값 # 처음에는 k = x이다가 각도가 720도가 되면 k값은 감소하기 시작 # k가 어느 값 이하가 되면 다시 증가하고 이를 반복 s.write(dict(x=degree, y=y)) time.sleep(0.1) if temp == 720: a = 1 elif temp == 10: a = 0 if a == 1: temp = temp - 10 elif a == 0: temp = temp + 10 degree = degree + 10 s.close()
{"/project.py": ["/input1.py", "/process.py", "/output.py"]}
69,905
EungSeon/project
refs/heads/master
/input1.py
# import RPi.GPIO as GPIO import time class controller(): def led(self, LED, signal_LED): self.LED = LED self.signal_LED = signal_LED t = time.time() print("controller class에서 LED를 동작하는 함수 입니다.") return t """ GPIO.setup(self.LED, GPIO.OUT, initial=GPIO.LOW) GPIO.setup(self.signal_LED, GPIO.IN) signal = GPIO.input(self.signal_LED) start_time = time.time() while(signal == 1): GPIO.output(self.LED, GPIO.HIGH) signal = GPIO.input(self.signal_LED) end_time = time.time() GPIO.output(self.LED, GPIO.LOW) time = end_time - srart_time return time """ def fan(self, FAN, signal_FAN, PWMA): self.FAN = FAN self.signal_FAN = signal_FAN self.PWMA = PWMA t = time.time() print("controller class에서 FAN을 동작하는 함수 입니다.") return t """ GPIO.setup(self.FAN, GPIO.OUT, initial=GPIO.LOW) GPIO.setup(self.PWMA, GPIO.OUT, initial=GPIO.LOW) GPIO.setup(self.signal_FAN, GPIO.IN) duty_ratio = 10 signal = GPIO.input(signal_FAN) p = GPIO.PWM(self.PWMA, 100) p.start(0) start_time = time.time() while(signal == 1): GPIO.output(self.FAN, GPIO.HIGH) for pw in range(0, 101, duty_ratio): p.ChangeDutyCycle(pw) signal = GPIO.input(self.signal_FAN) end_time = time.time() GPIO.output(self.FAN, GPIO.LOW) time = end_time - start_time return time """ def device3(self): t = time.time() print("controller class에서 device를 동작하는 함수 입니다.") return t """ # 가상화된 디바이스 LED를 동작시키고 동작시간(데이터)을 반환 def controller_led(LED, signal_LED): GPIO.setup(LED, GPIO.OUT, initial=GPIO.LOW) GPIO.setup(signal_LED, GPIO.IN) signal = GPIO.input(signal_LED) start_time = time.time() while(signal == 1): GPIO.output(LED, GPIO.HIGH) signal = GPIO.input(signal_LED) end_time = time.time() GPIO.output(LED, GPIO.LOW) time = end_time - start_time return time # 가상화된 디바이스 선풍기(모터를 이용한)를 동작시키고 동작시간(데이터)을 반환 def controller_fan(FAN, signal_FAN, PWMA): GPIO.setup(FAN, GPIO.OUT, initial=GPIO.LOW) GPIO.setup(PWMA, GPIO.OUT, initial=GPIO.LOW) GPIO.setup(signal_FAN, GPIO.IN) duty_ratio = 10 signal = GPIO.input(signal_FAN) p = GPIO.PWM(PWMA, 100) p.start(0) start_time = time.time() while(signal == 1): GPIO.output(FAN, GPIO.HIGH) for pw in range(0, 101, duty_ratio): p.ChangeDutyCycle(pw) signal = GPIO.input(signal_FAN) end_time = time.time() GPIO.output(FAN, GPIO.LOW) time = end_time - start_time return time # 다른 디바이스 - 아직 미정 def controller_device3(): """
{"/project.py": ["/input1.py", "/process.py", "/output.py"]}
69,906
EungSeon/project
refs/heads/master
/output.py
# 분석하고 그에 따른 필요한 output을 return class analysis: def analysis(self): print("analysis class에서 데이터를 분석하는 함수입니다.") print('output을 정한 후 출력 예정')
{"/project.py": ["/input1.py", "/process.py", "/output.py"]}
69,907
EungSeon/project
refs/heads/master
/project.py
# import RPi.GPIO as GPIO import time # GPIO.setmode(GPIO.BOARD) LED = 11 # LED 연결 핀번호 signal_LED = 10 # LED 동작여부 핀번호 FAN = 12 # FAN 연결 핀번호 signal_FAN = 13 # FAN 동작여부 핀번호 PWMA = 14 # PWM신호 발생 핀번호 import input1 a = input1.controller() time_led = a.led(LED, signal_LED) time_fan = a.fan(FAN, signal_FAN, PWMA) time_device = a.device3() print(time_led) print(time_fan) print(time_device) import process d = process.collectdata() d.data() import output result = output.analysis() result.analysis()
{"/project.py": ["/input1.py", "/process.py", "/output.py"]}
69,908
EungSeon/project
refs/heads/master
/clienttest.py
import bluetooth import thread import time import RPi.GPIO as GPIO import threading # Device Name DeviceName1 = "LED" DeviceName2 = "FAN" DeviceName3 = "CAR" # Port Setting LED = 7 FAN_EN = 31 FAN_Input1 = 33 FAN_Input2 = 35 CAR_Front_EN = 29 CAR_Front_Input1 = 23 CAR_Front_Input2 = 21 CAR_Behind_EN = 13 CAR_Behind_Input1 = 19 CAR_Behind_Input2 = 15 charging_station = 5 # sortdata function converts string about bluetooth data to list def sortdata(data): global device_signal_list global i a = 0 deviceNum = len(data) # Length of data variable is the number of device if i == 0: print "The Number of Device is %d" %deviceNum while a < deviceNum: k = int(data[a]) device_signal_list.append(k) a += 1 i += 1 else: while a < deviceNum: k = int(data[a]) device_signal_list[a] = k a += 1 # controller class sets devices in motion class Controller(): def led(self, deviceName, led_port, signal_led): self.deviceName = deviceName self.led_port = led_port self.signal_led = signal_led if self.signal_led == 1: GPIO.output(self.led_port, GPIO.HIGH) else: GPIO.output(self.led_port, GPIO.LOW) return def fan(self, deviceName, fan_en_port, fan_input1_port, fan_input2_port, signal_fan): self.deviceName = deviceName self.fan_en_port = fan_en_port self.fan_input1_port = fan_input1_port self.fan_input2_port = fan_input2_port self.signal_fan = signal_fan if self.signal_fan == 1: GPIO.output(self.fan_en_port, GPIO.HIGH) GPIO.output(self.fan_input1_port, GPIO.LOW) GPIO.output(self.fan_input2_port, GPIO.HIGH) else: GPIO.output(self.fan_en_port, GPIO.LOW) GPIO.output(self.fan_input1_port, GPIO.LOW) GPIO.output(self.fan_input2_port, GPIO.HIGH) return def car(self, deviceName, car_front_en_port, car_front_input1_port, car_front_input2_port, car_behind_en_port, car_behind_input1_port, car_behind_input2_port, charging_station_port, signal_car): self.deviceName = deviceName self.car_front_en_port = car_front_en_port self.car_front_input1_port = car_front_input1_port self.car_front_input2_port = car_front_input2_port self.car_behind_en_port = car_behind_en_port self.car_behind_input1_port = car_behind_input1_port self.car_behind_input2_port = car_behind_input2_port self.charging_station_port = charging_station_port self.signal_car = signal_car if self.signal_car == 1: GPIO.output(self.car_front_en_port, GPIO.HIGH) GPIO.output(self.car_front_input1_port, GPIO.LOW) GPIO.output(self.car_front_input2_port, GPIO.HIGH) GPIO.output(self.car_behind_en_port, GPIO.HIGH) GPIO.output(self.car_behind_input1_port, GPIO.LOW) GPIO.output(self.car_behind_input2_port, GPIO.HIGH) GPIO.output(self.charging_station_port, GPIO.LOW) else: GPIO.output(self.car_front_en_port, GPIO.LOW) GPIO.output(self.car_front_input1_port, GPIO.LOW) GPIO.output(self.car_front_input2_port, GPIO.HIGH) GPIO.output(self.car_behind_en_port, GPIO.LOW) GPIO.output(self.car_behind_input1_port, GPIO.LOW) GPIO.output(self.car_behind_input2_port, GPIO.HIGH) GPIO.output(self.charging_station_port, GPIO.HIGH) # FND class controls 7-segment class FND(): # Port setting(7-segment) def __init__(self): self.fndc0 = 40 self.fndc1 = 24 self.fndc2 = 22 self.fndc3 = 12 self.fnda = 16 self.fndb = 26 self.fndc = 37 self.fndd = 36 self.fnde = 32 self.fndf = 18 self.fndg = 38 self.position = 0 self.c0 = 0 self.c1 = 0 self.c2 = 0 self.c3 = 0 GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) GPIO.setup(self.fndc0, GPIO.OUT) GPIO.setup(self.fndc1, GPIO.OUT) GPIO.setup(self.fndc2, GPIO.OUT) GPIO.setup(self.fndc3, GPIO.OUT) GPIO.setup(self.fnda, GPIO.OUT) GPIO.setup(self.fndb, GPIO.OUT) GPIO.setup(self.fndc, GPIO.OUT) GPIO.setup(self.fndd, GPIO.OUT) GPIO.setup(self.fnde, GPIO.OUT) GPIO.setup(self.fndf, GPIO.OUT) GPIO.setup(self.fndg, GPIO.OUT) # Clear 7-segment - display 0000 def Clear(self): GPIO.output(self.fnda, GPIO.LOW) GPIO.output(self.fndb, GPIO.LOW) GPIO.output(self.fndc, GPIO.LOW) GPIO.output(self.fndd, GPIO.LOW) GPIO.output(self.fnde, GPIO.LOW) GPIO.output(self.fndf, GPIO.LOW) GPIO.output(self.fndg, GPIO.LOW) # Display Number def Val_0(self): GPIO.output(self.fnda, GPIO.HIGH) GPIO.output(self.fndb, GPIO.HIGH) GPIO.output(self.fndc, GPIO.HIGH) GPIO.output(self.fndd, GPIO.HIGH) GPIO.output(self.fnde, GPIO.HIGH) GPIO.output(self.fndf, GPIO.HIGH) GPIO.output(self.fndg, GPIO.LOW) def Val_1(self): GPIO.output(self.fnda, GPIO.LOW) GPIO.output(self.fndb, GPIO.HIGH) GPIO.output(self.fndc, GPIO.HIGH) GPIO.output(self.fndd, GPIO.LOW) GPIO.output(self.fnde, GPIO.LOW) GPIO.output(self.fndf, GPIO.LOW) GPIO.output(self.fndg, GPIO.LOW) def Val_2(self): GPIO.output(self.fnda, GPIO.HIGH) GPIO.output(self.fndb, GPIO.HIGH) GPIO.output(self.fndc, GPIO.LOW) GPIO.output(self.fndd, GPIO.HIGH) GPIO.output(self.fnde, GPIO.HIGH) GPIO.output(self.fndf, GPIO.LOW) GPIO.output(self.fndg, GPIO.HIGH) def Val_3(self): GPIO.output(self.fnda, GPIO.HIGH) GPIO.output(self.fndb, GPIO.HIGH) GPIO.output(self.fndc, GPIO.HIGH) GPIO.output(self.fndd, GPIO.HIGH) GPIO.output(self.fnde, GPIO.LOW) GPIO.output(self.fndf, GPIO.LOW) GPIO.output(self.fndg, GPIO.HIGH) def Val_4(self): GPIO.output(self.fnda, GPIO.LOW) GPIO.output(self.fndb, GPIO.HIGH) GPIO.output(self.fndc, GPIO.HIGH) GPIO.output(self.fndd, GPIO.LOW) GPIO.output(self.fnde, GPIO.LOW) GPIO.output(self.fndf, GPIO.HIGH) GPIO.output(self.fndg, GPIO.HIGH) def Val_5(self): GPIO.output(self.fnda, GPIO.HIGH) GPIO.output(self.fndb, GPIO.LOW) GPIO.output(self.fndc, GPIO.HIGH) GPIO.output(self.fndd, GPIO.HIGH) GPIO.output(self.fnde, GPIO.LOW) GPIO.output(self.fndf, GPIO.HIGH) GPIO.output(self.fndg, GPIO.HIGH) def Val_6(self): GPIO.output(self.fnda, GPIO.HIGH) GPIO.output(self.fndb, GPIO.LOW) GPIO.output(self.fndc, GPIO.HIGH) GPIO.output(self.fndd, GPIO.HIGH) GPIO.output(self.fnde, GPIO.HIGH) GPIO.output(self.fndf, GPIO.HIGH) GPIO.output(self.fndg, GPIO.HIGH) def Val_7(self): GPIO.output(self.fnda, GPIO.HIGH) GPIO.output(self.fndb, GPIO.HIGH) GPIO.output(self.fndc, GPIO.HIGH) GPIO.output(self.fndd, GPIO.LOW) GPIO.output(self.fnde, GPIO.LOW) GPIO.output(self.fndf, GPIO.LOW) GPIO.output(self.fndg, GPIO.LOW) def Val_8(self): GPIO.output(self.fnda, GPIO.HIGH) GPIO.output(self.fndb, GPIO.HIGH) GPIO.output(self.fndc, GPIO.HIGH) GPIO.output(self.fndd, GPIO.HIGH) GPIO.output(self.fnde, GPIO.HIGH) GPIO.output(self.fndf, GPIO.HIGH) GPIO.output(self.fndg, GPIO.HIGH) def Val_9(self): GPIO.output(self.fnda, GPIO.HIGH) GPIO.output(self.fndb, GPIO.HIGH) GPIO.output(self.fndc, GPIO.HIGH) GPIO.output(self.fndd, GPIO.HIGH) GPIO.output(self.fnde, GPIO.LOW) GPIO.output(self.fndf, GPIO.HIGH) GPIO.output(self.fndg, GPIO.HIGH) # Clear 7-segment - display nothing def Clear_C(self): GPIO.output(self.fndc0, GPIO.HIGH) GPIO.output(self.fndc1, GPIO.HIGH) GPIO.output(self.fndc2, GPIO.HIGH) GPIO.output(self.fndc3, GPIO.HIGH) # ON each digit def View(self, position): if position == 0: GPIO.output(self.fndc0, GPIO.LOW) elif position == 1: GPIO.output(self.fndc1, GPIO.LOW) elif position == 2: GPIO.output(self.fndc2, GPIO.LOW) elif position == 3: GPIO.output(self.fndc3, GPIO.LOW) def Value(self, position, val): self.Clear_C() if val == 0: self.Val_0() elif val == 1: self.Val_1() elif val == 2: self.Val_2() elif val == 3: self.Val_3() elif val == 4: self.Val_4() elif val == 5: self.Val_5() elif val == 6: self.Val_6() elif val == 7: self.Val_7() elif val == 8: self.Val_8() elif val == 9: self.Val_9() self.View(position) def fndview(self): if self.position == 0: self.Value(0, self.c0) elif self.position == 1: self.Value(1, self.c1) elif self.position == 2: self.Value(2, self.c2) else: self.Value(3, self.c3) self.position = 0 return self.position = self.position + 1 def thread_segment(aa): segment = FND() while True: global digit0 global digit1 global digit2 global digit3 segment.c0 = digit0 segment.c1 = digit1 segment.c2 = digit2 segment.c3 = digit3 segment.fndview() time.sleep(0.001) # Main if __name__ == '__main__': digit0 = 0 digit1 = 0 digit2 = 0 digit3 = 0 GPIO.setmode(GPIO.BOARD) device_signal_list = [] i = 0 aa = 10 # Bluetooth Connection client_sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM ) blport = 3 bd_addr = "B8:27:EB:15:09:34" # Server's address client_sock.connect((bd_addr, blport)) start = client_sock.recv(1024) print start client_sock.send('The connection with the client succeeded') # Device set Device1 = Controller() Device2 = Controller() Device3 = Controller() # GPIO setup GPIO.setwarnings(False) GPIO.setup(LED, GPIO.OUT, initial=GPIO.LOW) GPIO.setup(FAN_EN, GPIO.OUT, initial=GPIO.LOW) GPIO.setup(FAN_Input1, GPIO.OUT, initial=GPIO.LOW) GPIO.setup(FAN_Input2, GPIO.OUT, initial=GPIO.LOW) GPIO.setup(CAR_Front_EN, GPIO.OUT, initial=GPIO.LOW) GPIO.setup(CAR_Front_Input1, GPIO.OUT, initial=GPIO.LOW) GPIO.setup(CAR_Front_Input2, GPIO.OUT, initial=GPIO.LOW) GPIO.setup(CAR_Behind_EN, GPIO.OUT, initial=GPIO.LOW) GPIO.setup(CAR_Behind_Input1, GPIO.OUT, initial=GPIO.LOW) GPIO.setup(CAR_Behind_Input2, GPIO.OUT, initial=GPIO.LOW) GPIO.setup(charging_station, GPIO.OUT, initial=GPIO.HIGH) th = threading.Thread(target=thread_segment, args=(aa,)) th.start() while True: data = client_sock.recv(1024) client_sock.send('Get data') sortdata(data) print '-'*30 print 'string data :', data print 'list data :', device_signal_list print "Device's State" if device_signal_list[0] == 1: print '%s : ON' %DeviceName1 else: print '%s : OFF' %DeviceName1 if device_signal_list[1] == 1: print '%s : ON' %DeviceName2 else: print '%s : OFF' %DeviceName2 if device_signal_list[2] == 1: print '%s : ON' %DeviceName3 else: print '%s : OFF' %DeviceName3 # energy sort energy_str = client_sock.recv(1024) client_sock.send('Get energy') energy = int(energy_str) if energy >= 1000: digit0 = int(energy_str[3]) digit1 = int(energy_str[2]) digit2 = int(energy_str[1]) digit3 = int(energy_str[0]) elif energy < 1000 and energy >= 100: digit0 = int(energy_str[2]) digit1 = int(energy_str[1]) digit2 = int(energy_str[0]) digit3 = 0 elif energy < 100 and energy >= 10: digit0 = int(energy_str[1]) digit1 = int(energy_str[0]) digit2 = 0 digit3 = 0 elif energy <= 0: digit0 = 0 digit1 = 0 digit2 = 0 digit3 = 0 print 'There is no energy' print 'Amount of energy :', energy_str Device1.led(DeviceName1, LED, device_signal_list[0]) Device2.fan(DeviceName2, FAN_EN, FAN_Input1, FAN_Input2, device_signal_list[1]) Device3.car(DeviceName3, CAR_Front_EN, CAR_Front_Input1, CAR_Front_Input2, CAR_Behind_EN, CAR_Behind_Input1, CAR_Behind_Input2, charging_station, device_signal_list[2])
{"/project.py": ["/input1.py", "/process.py", "/output.py"]}
69,909
EungSeon/project
refs/heads/master
/servertest.py
import bluetooth import threading import math import time import datetime import Tkinter import RPi.GPIO as GPIO import subprocess blport = 3 server_addr = "B8:27:EB:15:09:34" # Amount of energy energy_amount = 5000 energy_amount_str = str(energy_amount) money = 35690 # Device Name DeviceName1 = "LED" DeviceName2 = "FAN" DeviceName3 = "CAR" device1_signal = 0 device2_signal = 0 device3_signal = 0 contract_signal = 0 data_lst = ['0', '0', '0'] operating_lst = [] time_lst = [] energy_lst = [] device1_start_time = 0.0 device1_dp_start_time = "" device2_start_time = 0.0 device2_dp_start_time = "" device3_start_time = 0.0 device3_dp_start_time = "" # collect data function collects data of devices and returns the energy consumption def collectdata(DeviceName, start, end, op_time): global operating_lst # Collect data at list global time_lst # Collect operating time at list global energy_lst # Collect amount of energy at list if DeviceName == "LED": energy_amount = round(op_time, 1) * 30 elif DeviceName == "FAN": energy_amount = round(op_time, 1) * 60 else: energy_amount = round(op_time, 1) * 300 k = "ON : " + start + ", OFF : " + end + ", Operating time : %.1f seconds, Energy consumption : %d, Device = %s" %(op_time, int(energy_amount), DeviceName) time = round(op_time, 1) # Save data, the type is list operating_lst.append(k) time_lst.append(time) energy_lst.append(energy_amount) length = len(operating_lst) i = 0 while i<length: print operating_lst[i] i = i+1 return energy_amount def information_led(): global operating_lst global time_lst global energy_lst print '' length = len(operating_lst) i = 0 time = 0.0 energy = 0.0 while i<length: data = operating_lst[i] device = data[-3] + data[-2] + data[-1] if device == 'LED': print operating_lst[i] time = time + time_lst[i] energy = energy + energy_lst[i] i = i+1 print 'Total operating time of LED : %.2f seconds' %time print 'Total energy consumption of LED : %d' %int(energy) print '' def information_fan(): global operating_lst global time_lst global energy_lst print '' length = len(operating_lst) i = 0 time = 0.0 energy = 0.0 while i<length: data = operating_lst[i] device = data[-3] + data[-2] + data[-1] if device == 'FAN': print operating_lst[i] time = time + time_lst[i] energy = energy + energy_lst[i] i = i+1 print 'Total operating time of FAN : %.2f seconds' %time print 'Total energy consumption of FAN : %d' %int(energy) print '' def information_car(): global operating_lst global time_lst global energy_lst print '' length = len(operating_lst) i = 0 time = 0.0 energy = 0.0 while i<length: data = operating_lst[i] device = data[-3] + data[-2] + data[-1] if device == 'CAR': print operating_lst[i] time = time + time_lst[i] energy = energy + energy_lst[i] i = i+1 print 'Total operating time of CAR : %.2f seconds' %time print 'Total energy consumption of CAR : %d' %int(energy) print '' def push_device1(): global device1_signal global data_lst # Datalist to send client via bluetooth global device1_start_time # Start time of Device1 global device1_dp_start_time # Start time of Device1(Display) global energy_amount global energy_amount_str global contract_signal global conn global addr global money if device1_signal == 0: # Device1 ON label1.config(text = 'ON') data_lst[0] = '1' device1_signal = 1 print '-'*30 print DeviceName1 + ' is ON' # Send data of current device state data = data_lst[0]+data_lst[1]+data_lst[2] print "Data : " + data conn.send(data) print 'Data transfer completed' words = conn.recv(1024) conn.send(energy_amount_str) words = conn.recv(1024) # Start time device1_start_time = time.time() device1_dp_start_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') elif device1_signal == 1: # Device1 OFF label1.config(text = 'OFF') data_lst[0] = '0' device1_signal = 0 print '-'*30 print DeviceName1 + ' is OFF' # Send data of current device state data = data_lst[0]+data_lst[1]+data_lst[2] print "Data : " + data conn.send(data) print 'Data transfer completed' words = conn.recv(1024) print '-'*30 # End time device1_end_time = time.time() operating_time = device1_end_time - device1_start_time device1_dp_end_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') energy = collectdata(DeviceName1, device1_dp_start_time, device1_dp_end_time, operating_time) energy_amount = energy_amount - int(energy) if contract_signal == 0 and energy_amount <0: print '' print 'There is no energy' print 'You need energy trading' print "You can't drive devices" print '' # Run energy transaction file pipe = subprocess.Popen("node trans.js", shell = True, stdout = subprocess.PIPE).stdout while True: f = open("nodetopython.txt", 'r') line = f.readline() if line == '0\n': f.close() else: print 'Energy trading completed' f = open("nodetopython.txt", 'r') lines = f.readlines() add_energy = lines[0] money_paid = lines[1] add_energy = int(add_energy) money_paid = int(money_paid) energy_amount = energy_amount + add_energy print 'Money before payment : %d$' %money money = money - money_paid print 'Money after payment : %d$' %money f.close() # Reset txt file is used to next energy trading f = open("nodetopython.txt", 'w') f.write('0\n') f.write('0') f.close() break elif contract_signal == 0 and energy_amount < 2000 and energy_amount >= 0: contract_signal = 1 print '' print 'There is not enough energy' print 'You need energy trading' print '' # Run energy transaction file pipe = subprocess.Popen("node trans.js", shell = True, stdout = subprocess.PIPE).stdout f = open("nodetopython.txt", 'r') line = f.readline() if line == '0\n': f.close() else: print 'Energy trading completed' contract_signal = 0 f = open("nodetopython.txt", 'r') lines = f.readlines() add_energy = lines[0] money_paid = lines[1] add_energy = int(add_energy) money_paid = int(money_paid) energy_amount = energy_amount + add_energy print 'Money before payment : %d$' %money money = money - money_paid print 'Money after payment : %d$' %money f.close() # Reset txt file is used to next energy trading f = open("nodetopython.txt", 'w') f.write('0\n') f.write('0') f.close() elif contract_signal == 1 and energy_amount < 2000 and energy_amount >= 0: print '' print 'There is not enough energy' print 'You need energy trading' print '' f = open("nodetopython.txt", 'r') line = f.readline() if line == '0\n': f.close() else: print 'Energy trading completed' contract_signal = 0 f = open("nodetopython.txt", 'r') lines = f.readlines() add_energy = lines[0] money_paid = lines[1] add_energy = int(add_energy) money_paid = int(money_paid) energy_amount = energy_amount + add_energy print 'Money before payment : %d$' %money money = money - money_paid print 'Money after payment : %d$' %money f.close() # Reset txt file is used to next energy trading f = open("nodetopython.txt", 'w') f.write('0\n') f.write('0') f.close() elif contract_signal == 1 and energy_amount < 0: print '' print 'There is no energy' print 'You need energy trading' print "You can't drive devices" print '' while True: f = open("nodetopython.txt", 'r') line = f.readline() if line == '0\n': f.close() else: print 'Energy trading completed' contract_signal = 0 f = open("nodetopython.txt", 'r') lines = f.readlines() add_energy = lines[0] money_paid = lines[1] add_energy = int(add_energy) money_paid = int(money_paid) energy_amount = energy_amount + add_energy print 'Money before payment : %d$' %money money = money - money_paid print 'Money after payment : %d$' %money f.close() # Reset txt file is used to next energy trading f = open("nodetopython.txt", 'w') f.write('0\n') f.write('0') f.close() break energy_amount_str = str(energy_amount) conn.send(energy_amount_str) words = conn.recv(1024) # Energy display print 'Amount of Energy : %d' %energy_amount def push_device2(): global device2_signal global data_lst # Datalist to send client via bluetooth global device2_start_time # Start time of Device2 global device2_dp_start_time # Start time of Device2(Display) global energy_amount global energy_amount_str global contract_signal global conn global addr global money if device2_signal == 0: # Device2 ON label2.config(text = 'ON') data_lst[1] = '1' device2_signal = 1 print '-'*30 print DeviceName2 + ' is ON' # Send data of current device state data = data_lst[0]+data_lst[1]+data_lst[2] print "Data : " + data conn.send(data) print 'Data transfer completed' words = conn.recv(1024) conn.send(energy_amount_str) words = conn.recv(1024) # Start time device2_start_time = time.time() device2_dp_start_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') elif device2_signal == 1: # Device2 OFF label2.config(text = 'OFF') data_lst[1] = '0' device2_signal = 0 print '-'*30 print DeviceName2 + ' is OFF' # Send data of current device state data = data_lst[0]+data_lst[1]+data_lst[2] print "Data : " + data conn.send(data) print 'Data transfer completed' words = conn.recv(1024) print '-'*30 # End time device2_end_time = time.time() operating_time = device2_end_time - device2_start_time device2_dp_end_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') energy = collectdata(DeviceName2, device2_dp_start_time, device2_dp_end_time, operating_time) energy_amount = energy_amount - int(energy) if contract_signal == 0 and energy_amount <0: print '' print 'There is no energy' print 'You need energy trading' print "You can't drive devices" print '' # Run energy transaction file pipe = subprocess.Popen("node trans.js", shell = True, stdout = subprocess.PIPE).stdout while True: f = open("nodetopython.txt", 'r') line = f.readline() if line == '0\n': f.close() else: print 'Energy trading completed' f = open("nodetopython.txt", 'r') lines = f.readlines() add_energy = lines[0] money_paid = lines[1] add_energy = int(add_energy) money_paid = int(money_paid) energy_amount = energy_amount + add_energy print 'Money before payment : %d$' %money money = money - money_paid print 'Money after payment : %d$' %money f.close() # Reset txt file is used to next energy trading f = open("nodetopython.txt", 'w') f.write('0\n') f.write('0') f.close() break elif contract_signal == 0 and energy_amount < 2000 and energy_amount >= 0: contract_signal = 1 print '' print 'There is not enough energy' print 'You need energy trading' print '' # Run energy transaction file pipe = subprocess.Popen("node trans.js", shell = True, stdout = subprocess.PIPE).stdout f = open("nodetopython.txt", 'r') line = f.readline() if line == '0\n': f.close() else: print 'Energy trading completed' contract_signal = 0 f = open("nodetopython.txt", 'r') lines = f.readlines() add_energy = lines[0] money_paid = lines[1] add_energy = int(add_energy) money_paid = int(money_paid) energy_amount = energy_amount + add_energy print 'Money before payment : %d$' %money money = money - money_paid print 'Money after payment : %d$' %money f.close() # Reset txt file is used to next energy trading f = open("nodetopython.txt", 'w') f.write('0\n') f.write('0') f.close() elif contract_signal == 1 and energy_amount < 2000 and energy_amount >= 0: print '' print 'There is not enough energy' print 'You need energy trading' print '' f = open("nodetopython.txt", 'r') line = f.readline() if line == '0\n': f.close() else: print 'Energy trading completed' contract_signal = 0 f = open("nodetopython.txt", 'r') lines = f.readlines() add_energy = lines[0] money_paid = lines[1] add_energy = int(add_energy) money_paid = int(money_paid) energy_amount = energy_amount + add_energy print 'Money before payment : %d$' %money money = money - money_paid print 'Money after payment : %d$' %money f.close() # Reset txt file is used to next energy trading f = open("nodetopython.txt", 'w') f.write('0\n') f.write('0') f.close() elif contract_signal == 1 and energy_amount < 0: print '' print 'There is no energy' print 'You need energy trading' print "You can't drive device" print '' while True: f = open("nodetopython.txt", 'r') line = f.readline() if line == '0\n': f.close() else: print 'Energy trading completed' contract_signal = 0 f = open("nodetopython.txt", 'r') lines = f.readlines() add_energy = lines[0] money_paid = lines[1] add_energy = int(add_energy) money_paid = int(money_paid) energy_amount = energy_amount + add_energy print 'Money before payment : %d$' %money money = money - money_paid print 'Money after payment : %d$' %money f.close() # Reset txt file is used to next energy trading f = open("nodetopython.txt", 'w') f.write('0\n') f.write('0') f.close() break energy_amount_str = str(energy_amount) conn.send(energy_amount_str) words = conn.recv(1024) # Energy display print 'Amount of Energy : %d' %energy_amount def push_device3(): global device3_signal global data_lst # Datalist to send client via bluetooth global device3_start_time # Start time of Device3 global device3_dp_start_time # Start time of Device3(Display) global energy_amount global energy_amount_str global contract_signal global conn global addr global money if device3_signal == 0: # Device3 ON label3.config(text = 'ON') data_lst[2] = '1' device3_signal = 1 print '-'*30 print DeviceName3 + ' is ON' # Send data of current device state data = data_lst[0]+data_lst[1]+data_lst[2] print "Data : " + data conn.send(data) print 'Data transfer completed' words = conn.recv(1024) conn.send(energy_amount_str) words = conn.recv(1024) # Start time device3_start_time = time.time() device3_dp_start_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') elif device3_signal == 1: # Device3 OFF label3.config(text = 'OFF') data_lst[2] = '0' device3_signal = 0 print '-'*30 print DeviceName3 + ' is OFF' # Send data of current device state data = data_lst[0]+data_lst[1]+data_lst[2] print "Data : " + data conn.send(data) print 'Data transfer completed' words = conn.recv(1024) print '-'*30 # End time device3_end_time = time.time() operating_time = device3_end_time - device3_start_time device3_dp_end_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') energy = collectdata(DeviceName3, device3_dp_start_time, device3_dp_end_time, operating_time) energy_amount = energy_amount - int(energy) if contract_signal == 0 and energy_amount <0: print '' print 'There is no energy' print 'You need energy trading' print "You can't drive devices" print '' # Run energy transaction file pipe = subprocess.Popen("node trans.js", shell = True, stdout = subprocess.PIPE).stdout while True: f = open("nodetopython.txt", 'r') line = f.readline() if line == '0\n': f.close() else: print 'Energy trading completed' f = open("nodetopython.txt", 'r') lines = f.readlines() add_energy = lines[0] money_paid = lines[1] add_energy = int(add_energy) money_paid = int(money_paid) energy_amount = energy_amount + add_energy print 'Money before payment : %d$' %money money = money - money_paid print 'Money after payment : %d$' %money f.close() # Reset txt file is used to next energy trading f = open("nodetopython.txt", 'w') f.write('0\n') f.write('0') f.close() break elif contract_signal == 0 and energy_amount < 2000 and energy_amount >= 0: contract_signal = 1 print '' print 'There is not enough energy' print 'You need energy trading' print '' # Run energy transaction file pipe = subprocess.Popen("node trans.js", shell = True, stdout = subprocess.PIPE).stdout f = open("nodetopython.txt", 'r') line = f.readline() if line == '0\n': f.close() else: print 'Energy trading completed' contract_signal = 0 f = open("nodetopython.txt", 'r') lines = f.readlines() add_energy = lines[0] money_paid = lines[1] add_energy = int(add_energy) money_paid = int(money_paid) energy_amount = energy_amount + add_energy print 'Money before payment : %d$' %money money = money - money_paid print 'Money after payment : %d$' %money f.close() # Reset txt file is used to next energy trading f = open("nodetopython.txt", 'w') f.write('0\n') f.write('0') f.close() elif contract_signal == 1 and energy_amount < 2000 and energy_amount >= 0: print '' print 'There is not enough energy' print 'You need energy trading' print '' f = open("nodetopython.txt", 'r') line = f.readline() if line == '0\n': f.close() else: print 'Energy trading completed' contract_signal = 0 f = open("nodetopython.txt", 'r') lines = f.readlines() add_energy = lines[0] money_paid = lines[1] add_energy = int(add_energy) money_paid = int(money_paid) energy_amount = energy_amount + add_energy print 'Money before payment : %d$' %money money = money - money_paid print 'Money after payment : %d$' %money f.close() # Reset txt file is used to next energy trading f = open("nodetopython.txt", 'w') f.write('0\n') f.write('0') f.close() elif contract_signal == 1 and energy_amount < 0: print '' print 'There is no energy' print 'You need energy trading' print "You can't drive device" print '' while True: f = open("nodetopython.txt", 'r') line = f.readline() if line == '0\n': f.close() else: print 'Energy trading completed' contract_signal = 0 f = open("nodetopython.txt", 'r') lines = f.readlines() add_energy = lines[0] money_paid = lines[1] add_energy = int(add_energy) money_paid = int(money_paid) energy_amount = energy_amount + add_energy print 'Money before payment : %d$' %money money = money - money_paid print 'Money after payment : %d$' %money f.close() # Reset txt file is used to next energy trading f = open("nodetopython.txt", 'w') f.write('0\n') f.write('0') f.close() break energy_amount_str = str(energy_amount) conn.send(energy_amount_str) words = conn.recv(1024) # Energy display print 'Amount of Energy : %d' %energy_amount if __name__ == '__main__': # Bluetooth Connection server_sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM ) server_sock.bind(("", blport)) server_sock.listen(100) print 'Waiting for connection with the client' print '' conn, addr = server_sock.accept() conn.send('The connection with the server succeeded') start = conn.recv(1024) print start print '-'*30 print 'Server addr :', server_addr print 'Client addr :', addr[0] print 'Port Number :', addr[1] print '-'*30 print '' print '' # Make txt file that is used to energy trading f = open("nodetopython.txt", 'w') f.write('0\n') f.write('0') f.close() # Send data and energy(Initial data is "000", Initial energy is 5000) data = "000" conn.send(data) words = conn.recv(1024) conn.send(energy_amount_str) words = conn.recv(1024) # GuI root = Tkinter.Tk() root.title('Device Controller') label1 = Tkinter.Label(root, padx = 10, pady = 10, font = 20, foreground = 'red', text = 'OFF') label2 = Tkinter.Label(root, padx = 10, pady = 10, font = 20, foreground = 'red', text = 'OFF') label3 = Tkinter.Label(root, padx = 10, pady = 10, font = 20, foreground = 'red', text = 'OFF') button1 = Tkinter.Button(root, height = 1, width = 30, padx = 20, pady = 10, text = DeviceName1, command = push_device1) button2 = Tkinter.Button(root, height = 1, width = 30, padx = 20, pady = 10, text = DeviceName2, command = push_device2) button3 = Tkinter.Button(root, height = 1, width = 30, padx = 20, pady = 10, text = DeviceName3, command = push_device3) button4 = Tkinter.Button(root, height = 1, width = 30, padx = 20, pady = 10, text = 'LED information', command = information_led) button5 = Tkinter.Button(root, height = 1, width = 30, padx = 20, pady = 10, text = 'FAN information', command = information_fan) button6 = Tkinter.Button(root, height = 1, width = 30, padx = 20, pady = 10, text = 'CAR information', command = information_car) label1.grid(row = 1, column = 1) label2.grid(row = 2, column = 1) label3.grid(row = 3, column = 1) button1.grid(row = 1, column = 0) button2.grid(row = 2, column = 0) button3.grid(row = 3, column = 0) button4.grid(row = 4, column = 0) button5.grid(row = 5, column = 0) button6.grid(row = 6, column = 0) root.mainloop()
{"/project.py": ["/input1.py", "/process.py", "/output.py"]}
69,910
EungSeon/project
refs/heads/master
/project#11.py
import numpy as np import matplotlib.pyplot as plt import math def f(t): return t * np.sin(2*np.pi*t) t1 = np.arange(0.0, 10.0, 0.1) plt.plot(t1, f(t1), 'b-') plt.xlabel('x') plt.ylabel('f(t)=tsint') plt.show()
{"/project.py": ["/input1.py", "/process.py", "/output.py"]}
69,911
EungSeon/project
refs/heads/master
/process.py
# 반환된 데이터를 리스트에 저장 - 분석은 차후 배울 간단한 머신 러닝을 사용할 예정 class collectdata: def data(self): print("collectdata class에서 데이터를 수집하는 함수 입니다.") LED_data = [] FAN_data = [] device_data = []
{"/project.py": ["/input1.py", "/process.py", "/output.py"]}
69,925
IMDweb/imddjango
refs/heads/master
/imdapp/urls.py
"""imdapp URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from imd import views urlpatterns = [ # Admin page url(r'^admin/', admin.site.urls), # Index page url(r'^$', views.index, name='index'), # Services pages url(r'^services/$', views.services, name='services'), url(r'^services/vehicle-wraps/$', views.vehicle_wraps, name='vehicle_wraps'), url(r'^services/tradeshows/$', views.tradeshows, name='tradeshows'), url(r'^services/web-design/$', views.web_design, name='web_design'), url(r'^services/design-service/$', views.design_service, name='design_service'), url(r'^services/signs-banners/$', views.signs_banners, name='signs_banners'), url(r'^services/printing/$', views.printing, name='printing'), url(r'^services/photography/$', views.photography, name='photography'), url(r'^services/window-wall-floor/$', views.window_wall_floor, name='window_wall_floor'), # Gallery Page url(r'^gallery/$', views.gallery, name="gallery"), # Contact Page url(r'^contact/$', views.contact, name='contact'), url(r'^thank_you/$', views.thanks, name='thanks'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
{"/imd/views.py": ["/imd/models.py", "/portfolio/models.py"], "/imd/admin.py": ["/imd/models.py"], "/portfolio/admin.py": ["/portfolio/models.py"]}
69,926
IMDweb/imddjango
refs/heads/master
/imd/views.py
from django.shortcuts import render, redirect from django.views.decorators.clickjacking import xframe_options_exempt from django.core.mail import BadHeaderError, send_mail, EmailMessage from django.http import HttpResponse, HttpResponseRedirect from django.template.loader import get_template from django.template import Context from imd.models import Service, Category, Document from portfolio.models import ImageGallery from imd.forms import ContactForm # Create your views here. @xframe_options_exempt def index(request): return render(request, 'index.html', { 'services': Service.objects.all(), 'category': Category.objects.all(), 'gallery': ImageGallery.objects.all(), }) @xframe_options_exempt def services(request): return render(request, 'services.html', { 'services': Service.objects.all(), 'category': Category.objects.all(), }) @xframe_options_exempt def contact(request): return render(request, 'contact.html', {}) @xframe_options_exempt def gallery(request): return render(request, 'gallery.html', { 'services': Service.objects.all(), 'category': Category.objects.all(), 'gallery': ImageGallery.objects.all(), }) @xframe_options_exempt def vehicle_wraps(request): partial = ImageGallery.objects.filter(category__title='Partial Wrap') full = ImageGallery.objects.filter(category__title='Full Wrap') color = ImageGallery.objects.filter(category__title='Color Change') return render(request, 'vehicle_wraps.html', { 'services': Service.objects.all(), 'category': Category.objects.all(), 'partial': partial, 'full': full, 'color': color, }) @xframe_options_exempt def tradeshows(request): return render(request, 'tradeshow.html', { 'service': Service.objects.all(), 'category':Category.objects.all(), }) @xframe_options_exempt def web_design(request): return render(request, 'web_design.html', { 'service': Service.objects.all(), 'category': Category.objects.all(), }) @xframe_options_exempt def design_service(request): return render(request, 'design_service.html', { 'service': Service.objects.all(), 'category': Category.objects.all(), }) @xframe_options_exempt def signs_banners(request): return render(request, 'signs_banners.html', { 'service': Service.objects.all(), 'category': Category.objects.all(), }) @xframe_options_exempt def printing(request): return render(request, 'printing.html', { 'service': Service.objects.all(), 'category': Category.objects.all(), }) @xframe_options_exempt def photography(request): return render(request, 'photography.html', { 'service': Service.objects.all(), 'category': Category.objects.all(), }) @xframe_options_exempt def window_wall_floor(request): return render(request, 'window_wall_floor.html', { 'service': Service.objects.all(), 'category': Category.objects.all(), }) @xframe_options_exempt def contact(request): if request.method == 'GET': form = ContactForm else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['contact_subject'] email = form.cleaned_data['contact_email'] first_name = form.cleaned_data['contact_name'] last_name = form.cleaned_data['contact_last_name'] message = form.cleaned_data['contact_message'] template = get_template('contact_template.txt') context = Context({ 'contact_first_name': first_name, 'contact_last_name': last_name, 'contact_email': email, 'contact_subject': subject, 'message': message, }) content = template.render(context) email_message = EmailMessage( "New Contact Message", content, email, ['jesus@imd-sd.com'] ) try: email_message.send() except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('thanks') return render(request, 'contact.html', { 'form': form, }) @xframe_options_exempt def thanks(request): return render(request, 'thank_you.html')
{"/imd/views.py": ["/imd/models.py", "/portfolio/models.py"], "/imd/admin.py": ["/imd/models.py"], "/portfolio/admin.py": ["/portfolio/models.py"]}
69,927
IMDweb/imddjango
refs/heads/master
/portfolio/models.py
from __future__ import unicode_literals from django.db import models from imd import models as imd # Create your models here. class ImageGallery(models.Model): name = models.CharField(max_length=60) category = models.ForeignKey('imd.Service') image = models.ImageField(upload_to='galley/', blank=False, null=False) thumbnail = models.ImageField(upload_to='gallery/thumbnail/', blank=False, null=False) desc = models.TextField(max_length=250) def __unicode__(self): return "%s" % self.name def create_thumbnail(self): # if there are no image if not self.image: return from PIL import Image from cStringIO import StringIO from django.core.files.uploadedfile import SimpleUploadedFile import os # max Thumbnail side THUMBNAIL_SIZE = (250, 250) DJANGO_TYPE = self.image.file.content_type if DJANGO_TYPE == 'image/jpeg': PIL_TYPE = 'jpeg' FILE_EXTENTION = 'jpg' elif DJANGO_TYPE == 'image/png': PIL_TYPE = 'png' FILE_EXTENTION = 'png' #open original photo image = Image.open(StringIO(self.image.read())) image.thumbnail(THUMBNAIL_SIZE, Image.ANTIALIAS) # save thumbnail temp_handle = StringIO() image.save(temp_handle, PIL_TYPE) temp_handle.seek(0) # save image to a SimpleUplodedFile to save into ImageField suf = SimpleUploadedFile(os.path.split(self.image.name)[-1], temp_handle.read(), content_type=DJANGO_TYPE) # save SimpleUploadedFile into imagefield self.thumbnail.save('%s_thumbnail.%s' % (os.path.splitext(suf.name)[0], FILE_EXTENTION), suf, save=False) def save(self): #create thumbnail self.create_thumbnail() #self.resizeImage() super(ImageGallery, self).save()
{"/imd/views.py": ["/imd/models.py", "/portfolio/models.py"], "/imd/admin.py": ["/imd/models.py"], "/portfolio/admin.py": ["/portfolio/models.py"]}
69,928
IMDweb/imddjango
refs/heads/master
/portfolio/migrations/0002_auto_20160526_1414.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-05-26 21:14 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('portfolio', '0001_initial'), ] operations = [ migrations.AlterField( model_name='imagegallery', name='category', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='imd.Service'), ), ]
{"/imd/views.py": ["/imd/models.py", "/portfolio/models.py"], "/imd/admin.py": ["/imd/models.py"], "/portfolio/admin.py": ["/portfolio/models.py"]}
69,929
IMDweb/imddjango
refs/heads/master
/imd/models.py
from __future__ import unicode_literals import os from django.db import models from django.db.models import permalink # Create your models here. def upload_images_to(instance, filename): return os.path.join("images/services/", filename) class Service(models.Model): title = models.CharField(max_length=100, unique=True) slug = models.SlugField(max_length=100, unique=True) category = models.ForeignKey('imd.Category') description = models.TextField() image = models.ImageField(upload_to=upload_images_to, blank=True) def __unicode__(self): return "%s service" % self.title @permalink def get_absolute_url(self): return ('view_service', None, { 'title': self.slug }) class Category(models.Model): name = models.CharField(max_length=100, unique=True) slug = models.SlugField(max_length=100, unique=True) desc = models.TextField() def __unicode__(self): return "%s" % self.name @permalink def get_absolute_url(self): return ('view_service_category', None, { 'slug': self.slug }) class Document(models.Model): docfile = models.FileField(upload_to='documents/%y/%m/', blank=True, null=True)
{"/imd/views.py": ["/imd/models.py", "/portfolio/models.py"], "/imd/admin.py": ["/imd/models.py"], "/portfolio/admin.py": ["/portfolio/models.py"]}
69,930
IMDweb/imddjango
refs/heads/master
/imd/admin.py
from django.contrib import admin from imd.models import Service, Category # Register your models here. class ServiceAdmin(admin.ModelAdmin): exclude = ['posted'] prepopulated_fields = { 'slug': ('title',)} class CategoryAdmin(admin.ModelAdmin): prepopulated_fields = { 'slug': ('name',)} admin.site.register(Service, ServiceAdmin) admin.site.register(Category, CategoryAdmin)
{"/imd/views.py": ["/imd/models.py", "/portfolio/models.py"], "/imd/admin.py": ["/imd/models.py"], "/portfolio/admin.py": ["/portfolio/models.py"]}
69,931
IMDweb/imddjango
refs/heads/master
/portfolio/admin.py
from django.contrib import admin from portfolio.models import ImageGallery # Register your models here. admin.site.register(ImageGallery)
{"/imd/views.py": ["/imd/models.py", "/portfolio/models.py"], "/imd/admin.py": ["/imd/models.py"], "/portfolio/admin.py": ["/portfolio/models.py"]}
69,932
IMDweb/imddjango
refs/heads/master
/imd/apps.py
from __future__ import unicode_literals from django.apps import AppConfig class ImdConfig(AppConfig): name = 'imd'
{"/imd/views.py": ["/imd/models.py", "/portfolio/models.py"], "/imd/admin.py": ["/imd/models.py"], "/portfolio/admin.py": ["/portfolio/models.py"]}
69,933
IMDweb/imddjango
refs/heads/master
/portfolio/migrations/0001_initial.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2016-02-18 21:35 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('imd', '0001_initial'), ] operations = [ migrations.CreateModel( name='ImageGallery', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=60)), ('image', models.ImageField(upload_to='galley/')), ('thumbnail', models.ImageField(upload_to='gallery/thumbnail/')), ('desc', models.TextField(max_length=250)), ('category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='imd.Category')), ], ), ]
{"/imd/views.py": ["/imd/models.py", "/portfolio/models.py"], "/imd/admin.py": ["/imd/models.py"], "/portfolio/admin.py": ["/portfolio/models.py"]}
69,939
maloi/django-informant
refs/heads/master
/informant/admin.py
from django.contrib import admin from django.template.loader import render_to_string from django.utils.translation import ugettext_lazy as _ from informant.models import Newsletter, Recipient class NewsletterAdmin(admin.ModelAdmin): list_display = ('subject', 'date', 'testing_emails', 'sent', 'approved', 'preview_url',) ordering = ('-date',) actions = ['reset_sent_flag', 'send_test'] def formfield_for_dbfield(self, db_field, **kwargs): if db_field.name == 'content': kwargs['initial'] = render_to_string('informant/mail/newsletter.html') return super(NewsletterAdmin, self).formfield_for_dbfield(db_field, **kwargs) def reset_sent_flag(self, request, queryset): queryset.update(sent=False) reset_sent_flag.short_description = _('Send again') def send_test(self, request, queryset): for n in queryset: n.send_test() send_test.short_description = _('Send to testing emails') class RecipientAdmin(admin.ModelAdmin): fields = ('email', 'first_name', 'last_name', 'sent', 'deleted', 'activated',) list_display = ('email', 'first_name', 'last_name', 'sent', 'deleted', 'activated', 'date', 'md5',) search_fields = ('email',) admin.site.register(Newsletter, NewsletterAdmin) admin.site.register(Recipient, RecipientAdmin)
{"/informant/admin.py": ["/informant/models.py"], "/informant/newman_admin.py": ["/informant/models.py"], "/informant/management/commands/send_newsletter.py": ["/informant/models.py"], "/informant/views.py": ["/informant/models.py", "/informant/forms.py"], "/informant/tasks.py": ["/informant/models.py"]}
69,940
maloi/django-informant
refs/heads/master
/informant/urls.py
from django.conf.urls.defaults import patterns, url from django.template.defaultfilters import slugify from django.utils.translation import ugettext_lazy as _ urlpatterns = patterns('informant.views', url('^%s/$' % slugify(_('subscribe')), 'subscribe', name='informant_subscribe'), url('^%s/([0-9a-f]{32})/$' % slugify(_('unsubscribe')), 'unsubscribe', name='informant_unsubscribe'), url('^%s/([0-9a-f]{32})/$' % slugify(_('activate')), 'activate', name='informant_activate'), url('^%s/([0-9]*)/$' % slugify(_('preview')), 'preview', name='informant_preview'), )
{"/informant/admin.py": ["/informant/models.py"], "/informant/newman_admin.py": ["/informant/models.py"], "/informant/management/commands/send_newsletter.py": ["/informant/models.py"], "/informant/views.py": ["/informant/models.py", "/informant/forms.py"], "/informant/tasks.py": ["/informant/models.py"]}
69,941
maloi/django-informant
refs/heads/master
/informant/newman_admin.py
''' Created on 10.10.2011 @author: xaralis ''' from django.template.loader import render_to_string import ella_newman as newman from informant.models import Newsletter, Recipient class NewsletterAdmin(newman.NewmanModelAdmin): list_display = ('subject', 'date', 'testing_emails', 'sent', 'approved', 'preview_url',) ordering = ('-date',) def formfield_for_dbfield(self, db_field, **kwargs): if db_field.name == 'content': kwargs['initial'] = render_to_string('informant/mail/newsletter.html') return super(NewsletterAdmin, self).formfield_for_dbfield(db_field, **kwargs) class RecipientAdmin(newman.NewmanModelAdmin): fields = ('email', 'first_name', 'last_name', 'sent', 'deleted',) list_display = ('email', 'first_name', 'last_name', 'sent', 'deleted', 'date', 'md5',) search_fields = ('email',) newman.site.register(Newsletter, NewsletterAdmin) newman.site.register(Recipient, RecipientAdmin)
{"/informant/admin.py": ["/informant/models.py"], "/informant/newman_admin.py": ["/informant/models.py"], "/informant/management/commands/send_newsletter.py": ["/informant/models.py"], "/informant/views.py": ["/informant/models.py", "/informant/forms.py"], "/informant/tasks.py": ["/informant/models.py"]}
69,942
maloi/django-informant
refs/heads/master
/informant/management/commands/send_newsletter.py
from django.conf import settings from django.core.management.base import NoArgsCommand from informant.models import Newsletter NEWSLETTER_EMAIL = settings.NEWSLETTER_EMAIL class Command(NoArgsCommand): help = "Send undelivered recipes newsletters" def handle_noargs(self, **options): Newsletter.objects.send_all()
{"/informant/admin.py": ["/informant/models.py"], "/informant/newman_admin.py": ["/informant/models.py"], "/informant/management/commands/send_newsletter.py": ["/informant/models.py"], "/informant/views.py": ["/informant/models.py", "/informant/forms.py"], "/informant/tasks.py": ["/informant/models.py"]}
69,943
maloi/django-informant
refs/heads/master
/informant/forms.py
from django import forms class SubscribleNewsForm(forms.Form): email = forms.EmailField() first_name = forms.CharField(required=False) last_name = forms.CharField(required=False) surname = forms.CharField(required=False) back_url = forms.CharField(required=False)
{"/informant/admin.py": ["/informant/models.py"], "/informant/newman_admin.py": ["/informant/models.py"], "/informant/management/commands/send_newsletter.py": ["/informant/models.py"], "/informant/views.py": ["/informant/models.py", "/informant/forms.py"], "/informant/tasks.py": ["/informant/models.py"]}
69,944
maloi/django-informant
refs/heads/master
/informant/process.py
__author__ = 'xaralis'
{"/informant/admin.py": ["/informant/models.py"], "/informant/newman_admin.py": ["/informant/models.py"], "/informant/management/commands/send_newsletter.py": ["/informant/models.py"], "/informant/views.py": ["/informant/models.py", "/informant/forms.py"], "/informant/tasks.py": ["/informant/models.py"]}
69,945
maloi/django-informant
refs/heads/master
/informant/models.py
from datetime import datetime import hashlib import logging import re import sys from django.conf import settings from django.contrib.sites.models import Site from django.core.exceptions import ImproperlyConfigured from django.core.mail import EmailMultiAlternatives, get_connection from django.db import models from django.template import Template, Context from django.template.loader import render_to_string from django.utils import translation from django.utils.safestring import mark_safe from django.utils.translation import ugettext_lazy as _ if hasattr(settings, 'INFORMANT_TESTING_EMAILS'): TESTING_EMAILS = settings.INFORMANT_TESTING_EMAILS elif settings.MANAGERS: TESTING_EMAILS = [m[1] for m in settings.MANAGERS] else: TESTING_EMAILS = '' try: NEWSLETTER_EMAIL = settings.NEWSLETTER_EMAIL except AttributeError: raise ImproperlyConfigured('NEWSLETTER_EMAIL setting is missing but required.') # Fake md5 MD5_MARK = '00112233445566778899aabbccddeeff' MD5_MARK_PATT = re.compile(MD5_MARK) logger = logging.getLogger(__name__) class NewsletterManager(models.Manager): def send_all(self): translation.activate(settings.LANGUAGE_CODE) # Newsletters, which have approved and have not delivered newsletters = Newsletter.objects.filter(approved=True, sent=False, date__lte=datetime.now()) connection = get_connection() for newsletter in newsletters: newsletter.send(connection=connection) class Newsletter(models.Model): subject = models.CharField(_('Subject'), max_length=128) content = models.TextField(_('Content')) date = models.DateTimeField(_('Date'), default=datetime.now) sent = models.BooleanField(_('Sent'), default=False, editable=False) testing_emails = models.CharField(_('Testing emails'), max_length=255, default=TESTING_EMAILS) approved = models.BooleanField(_('Approved'), default=False) objects = NewsletterManager() class Meta: verbose_name = _('Newsletter') verbose_name_plural = _('Newsletters') ordering = ('date',) def __unicode__(self): return self.subject @models.permalink def get_absolute_url(self): return ('informant_preview', (self.pk,)) def get_domain_url(self): return 'http://%s%s' % ( Site.objects.get_current().domain, self.get_absolute_url() ) def preview_url(self): return mark_safe('<a target="_blank" href="%s">URL</a>' % self.get_absolute_url()) preview_url.allow_tags = True preview_url.short_description = _('Preview') def _prep_content(self): # Prepare context c = Context({ 'newsletter': self, 'site': Site.objects.get_current(), 'recipient': {'md5': MD5_MARK}, 'MEDIA_URL': settings.MEDIA_URL, 'STATIC_URL': settings.STATIC_URL }) # Render parts content_html_ = Template(self.content).render(c) content_txt_ = render_to_string('informant/mail/base.txt', c) return content_html_, content_txt_ def send(self, connection=None): content_html_, content_txt_ = self._prep_content() # Recipients, who have not got newsletter recipients = Recipient.objects.filter(sent=False, deleted=False, activated=True) for recipient in recipients: # Replace fake md5 content_html = re.sub(MD5_MARK_PATT, recipient.md5, content_html_) content_txt = re.sub(MD5_MARK_PATT, recipient.md5, content_txt_) # Send mail msg = EmailMultiAlternatives(self.subject, content_txt, NEWSLETTER_EMAIL, (recipient.email,)) msg.attach_alternative(content_html, 'text/html') try: if connection is None: connection = get_connection() connection.send_messages((msg,)) except Exception, e: logger.warning('Couldnt deliver: %s - %s' % (recipient.email, str(e))) # Set recipient delivered flag recipient.sent = True recipient.save() # If newsletter was sent, set newsletter delivered flag self.sent = True self.save() # And clear recipients delivered flag Recipient.objects.all().update(sent=False) def send_test(self): content_html, content_txt = self._prep_content() recipients = self.testing_emails.split(',') # Send mail msg = EmailMultiAlternatives(self.subject, content_txt, NEWSLETTER_EMAIL, recipients) msg.attach_alternative(content_html, 'text/html') try: connection = get_connection() connection.send_messages((msg,)) except Exception, e: logger.warning('Couldnt deliver: %s' % str(e)) class Recipient(models.Model): email = models.EmailField(_('Email')) last_name = models.CharField(_('Lastname'), max_length=50) first_name = models.CharField(_('Firstname'), max_length=50) date = models.DateTimeField(_('Created')) sent = models.BooleanField(_('Sent'), default=False) deleted = models.BooleanField(_('Deleted'), default=False) activated = models.BooleanField(_('Activated'), default=False) md5 = models.CharField(_('MD5'), max_length=32) class Meta: verbose_name = _('Recipient') verbose_name_plural = _('Recipients') ordering = ('email',) def __unicode__(self): return self.email def do_md5(self): m = hashlib.md5() m.update(self.email) m.update(str(self.date)) return m.hexdigest() def save(self, *args, **kwargs): if self.date == None or self.md5 == None: self.date = datetime.now() self.md5 = self.do_md5() super(Recipient, self).save(*args, **kwargs) def to_dict(self): return { 'username': self.email }
{"/informant/admin.py": ["/informant/models.py"], "/informant/newman_admin.py": ["/informant/models.py"], "/informant/management/commands/send_newsletter.py": ["/informant/models.py"], "/informant/views.py": ["/informant/models.py", "/informant/forms.py"], "/informant/tasks.py": ["/informant/models.py"]}
69,946
maloi/django-informant
refs/heads/master
/informant/migrations/0003_auto__add_field_recipient_last_name__add_field_recipient_first_name.py
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Recipient.last_name' db.add_column(u'informant_recipient', 'last_name', self.gf('django.db.models.fields.CharField')(default='', max_length=50), keep_default=False) # Adding field 'Recipient.first_name' db.add_column(u'informant_recipient', 'first_name', self.gf('django.db.models.fields.CharField')(default='', max_length=50), keep_default=False) def backwards(self, orm): # Deleting field 'Recipient.last_name' db.delete_column(u'informant_recipient', 'last_name') # Deleting field 'Recipient.first_name' db.delete_column(u'informant_recipient', 'first_name') models = { u'informant.newsletter': { 'Meta': {'ordering': "('date',)", 'object_name': 'Newsletter'}, 'approved': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'content': ('django.db.models.fields.TextField', [], {}), 'date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'sent': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'subject': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'testing_emails': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '255'}) }, u'informant.recipient': { 'Meta': {'ordering': "('email',)", 'object_name': 'Recipient'}, 'date': ('django.db.models.fields.DateTimeField', [], {}), 'deleted': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '50'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '50'}), 'md5': ('django.db.models.fields.CharField', [], {'max_length': '32'}), 'sent': ('django.db.models.fields.BooleanField', [], {'default': 'False'}) } } complete_apps = ['informant']
{"/informant/admin.py": ["/informant/models.py"], "/informant/newman_admin.py": ["/informant/models.py"], "/informant/management/commands/send_newsletter.py": ["/informant/models.py"], "/informant/views.py": ["/informant/models.py", "/informant/forms.py"], "/informant/tasks.py": ["/informant/models.py"]}
69,947
maloi/django-informant
refs/heads/master
/informant/views.py
from django.conf import settings from django.core.mail import send_mail from django.contrib.sites.models import Site from django.http import HttpResponse, Http404, HttpResponseRedirect, \ HttpResponseForbidden from django.shortcuts import render, get_object_or_404 from django.template import Template, Context from django.template.loader import render_to_string from django.core.urlresolvers import reverse from informant.models import Recipient, Newsletter from informant.forms import SubscribleNewsForm def subscribe(request): if request.method == 'POST': f = SubscribleNewsForm(request.POST) if f.is_valid(): # Drop spam - field surname must be empty if f.cleaned_data['surname'] != '': return HttpResponseForbidden() # Save email if Recipient.objects.filter(email=f.cleaned_data['email']).count() == 0: # If email doesn't exist, save email r = Recipient(email=f.cleaned_data['email'], first_name=f.cleaned_data['first_name'], last_name=f.cleaned_data['last_name'], ) r.save() link = request.build_absolute_uri(reverse('informant_activate', args=(r.md5, ))) message = render_to_string('informant/mail/activation_email.html', {'email': r.email, 'first_name': r.first_name, 'link': link, } ) subject = getattr(settings, 'NEWSLETTER_ACTIVATION_SUBJECT', '') send_mail( subject, message, settings.NEWSLETTER_EMAIL, # Email From [f.cleaned_data['email']], ) else: # If email exists, clear deleted flag and set new created date r = Recipient.objects.get(email=f.cleaned_data['email']) if request.POST.get('subscribe', None) == 'unsubscribe': return unsubscribe(request, r.md5) r.first_name = f.cleaned_data['first_name'] r.last_name = f.cleaned_data['last_name'] r.sent = False r.deleted = False r.date = None r.save() if not request.is_ajax(): url = f.cleaned_data['back_url'] return HttpResponseRedirect(url) else: return render( request, 'informant/management/subscribe_ok.html', {'subscribe_email': r.email}) else: url = request.POST.get('back_url', '/') email = request.POST.get('email', '@') first_name = request.POST.get('first_name', '') last_name = request.POST.get('last_name', '') return render( request, 'informant/management/subscribe_error.html', {'back_url': url, 'subscribe_email': email, 'first_name': first_name, 'last_name': last_name, }, status=400) raise Http404 def activate(request, recipient_hash): try: r = Recipient.objects.get(md5=recipient_hash, activated=False) except: # Recipient does not exist return HttpResponseForbidden() r.activated = True r.save() return render(request, 'informant/management/activated.html', {'recipient': r}) def unsubscribe(request, recipient_hash): try: r = Recipient.objects.get(md5=recipient_hash, deleted=False) except: # Recipient does not exist return HttpResponseForbidden() r.deleted = True r.save() return render(request, 'informant/management/unsubscribed.html', {'recipient': r}) def preview(request, pk): # If newsletter doesn't exist, return 404 newsletter = get_object_or_404(Newsletter, pk=pk) # If newsletter has not been sent and user has not been logged, return 404 if not newsletter.approved and not request.user.is_authenticated(): raise Http404 md5_mark = '00112233445566778899aabbccddeeff' c = Context({ 'newsletter': newsletter, 'site': Site.objects.get_current(), 'recipient': {'md5': md5_mark}, 'MEDIA_URL': settings.MEDIA_URL, 'STATIC_URL': settings.STATIC_URL }) t = Template(newsletter.content) return HttpResponse(t.render(c))
{"/informant/admin.py": ["/informant/models.py"], "/informant/newman_admin.py": ["/informant/models.py"], "/informant/management/commands/send_newsletter.py": ["/informant/models.py"], "/informant/views.py": ["/informant/models.py", "/informant/forms.py"], "/informant/tasks.py": ["/informant/models.py"]}
69,948
maloi/django-informant
refs/heads/master
/informant/tasks.py
from celery.task import Task from informant.models import Newsletter __author__ = 'xaralis' class SendNewslettersTask(Task): def run(self, **kwargs): return Newsletter.objects.send_all()
{"/informant/admin.py": ["/informant/models.py"], "/informant/newman_admin.py": ["/informant/models.py"], "/informant/management/commands/send_newsletter.py": ["/informant/models.py"], "/informant/views.py": ["/informant/models.py", "/informant/forms.py"], "/informant/tasks.py": ["/informant/models.py"]}
69,952
jocafa/JCF_Shortcuts
refs/heads/main
/panels.py
import bpy from . import constants as const from . import operators as ops class JCF_RenderShortcutsPanel(bpy.types.Panel): """Jocafa Render Shortcuts Panel""" bl_label = "Jocafa Render Shortcuts" bl_idname = "JCF_PT_jcf_render_shortcuts" bl_space_type = 'PROPERTIES' bl_region_type = 'WINDOW' bl_context = "render" bl_category = "Jocafa" @classmethod def poll(cls, context): return True def draw_header(self, context): layout = self.layout layout.label(text="", icon="SOLO_ON") def draw(self, context): scene = context.scene layout = self.layout layout.label(text="Resolution, Scale, and Sampling", icon='OUTPUT') row = layout.row(align=True) # Quick list of resolutions i = 0 for res in const.resolutions: row.operator(ops.JCF_OT_set_render_size.bl_idname, text=res['name']).index = i i += 1 # Quick list of scales row = layout.row(align=True) for s in const.scales: row.operator(ops.JCF_OT_set_render_scale.bl_idname, text=s[0]).scale = s[1] * 100 row = layout.row(align=True) for s in const.samples: row.operator(ops.JCF_OT_set_render_samples.bl_idname, text=s['name']).samples = s['value'] # Compositing row = layout.row(align=True) row.prop(scene.render, "use_compositing") row.prop(scene.render, "use_sequencer") class JCF_ShortcutsPanel(bpy.types.Panel): """Jocafa Shortcuts Panel""" bl_label = "Jocafa Shortcuts" bl_idname = "JCF_PT_jcf_shortcuts" bl_space_type = 'VIEW_3D' bl_region_type = 'UI' #bl_context = "objectmode" bl_category = "Jocafa" @classmethod def poll(cls, context): return True def draw(self, context): layout = self.layout scene = context.scene jcf_props = scene.jcf_props overlay = context.space_data.overlay shading = context.space_data.shading # Viewport overlay shortcuts box = layout.box() row = box.row() row.prop( jcf_props, "overlays_expanded", icon='TRIA_DOWN' if jcf_props.overlays_expanded else 'TRIA_RIGHT', icon_only=True, emboss=False ) row.label(text="Viewport Overlays", icon='OVERLAY') if jcf_props.overlays_expanded: row = box.row(align=True) row.prop(overlay, "show_wireframes", text="") row.prop(overlay, "wireframe_threshold", text="Wireframe") row = box.row(align=True) row.prop(overlay, "show_vertex_normals", text="", icon='NORMALS_VERTEX') row.prop(overlay, "show_split_normals", text="", icon='NORMALS_VERTEX_FACE') row.prop(overlay, "show_face_normals", text="", icon='NORMALS_FACE') row.prop(overlay, "normals_length", text="Size") row = box.row(align=True) row.prop(overlay, "show_face_orientation", text="Face Orientation") row = box.row(align=True) row.prop(shading, "show_xray", text="") row.prop(shading, "xray_alpha", text="X-Ray") layout.separator() row = layout.row(align = True) # Camera Shortcuts layout.label(text="Camera", icon='CAMERA_DATA') row = layout.row(align=True) row.prop(scene.camera.data.dof, "use_dof", text="DOF") row.prop(scene.camera_settings, "enable_ae", text="AE") row.prop(scene.view_settings, "exposure") row = layout.row(align=True) row.prop(scene.camera.data, "lens", text="Lens", icon='DRIVER_ROTATIONAL_DIFFERENCE') row.prop(scene.camera.data.dof, "focus_distance", text="Dist", icon='DRIVER_DISTANCE') row.prop(scene.camera.data.dof, "aperture_fstop", text="F-Stop", icon='PROP_ON') layout.separator() # HDRI Sun Aligner shortcuts layout.label(text="HDRI Sun Aligner", icon='LIGHT_SUN') row = layout.row(align=True) row.operator('hdrisa.dummy', text="Sun Position") row.operator('hdrisa.rotate', text="Rotate Active") # Quick Objects layout.label(text="Quick Objects", icon='MESH_MONKEY') row = layout.row(); row.operator(ops.JCF_OT_add_tetrasphere.bl_idname) #layout.separator() # DEBUGGING #layout.label(text="DEBUG", icon='TOOL_SETTINGS') #row = layout.row(); #row.operator(ops.JCF_OT_debug.bl_idname)
{"/panels.py": ["/__init__.py"], "/operators.py": ["/__init__.py"], "/__init__.py": ["/panels.py", "/operators.py"]}
69,953
jocafa/JCF_Shortcuts
refs/heads/main
/operators.py
import bpy from . import constants as const class JCF_OT_debug(bpy.types.Operator): """Breakpoint for debugging and inspecting""" bl_idname = "jcf.debug" bl_label = "Debug" bl_options = {'REGISTER'} def execute(self, context): data = bpy.data print("JCF DEBUG") return {'FINISHED'} class JCF_OT_set_render_size(bpy.types.Operator): """Set Render Size""" bl_idname = "jcf.set_render_size" bl_label = "Set Render Size" bl_options = {'REGISTER'} index: bpy.props.IntProperty(default=0) def execute(self, context): bpy.context.scene.render.resolution_x = const.resolutions[self.index]['width'] bpy.context.scene.render.resolution_y = const.resolutions[self.index]['height'] return {'FINISHED'} class JCF_OT_set_render_scale(bpy.types.Operator): """Set Render Size""" bl_idname = "jcf.set_render_scale" bl_label = "Set Render Scale" bl_options = {'REGISTER'} scale: bpy.props.FloatProperty(default=100.0) def execute(self, context): bpy.context.scene.render.resolution_percentage = self.scale return {'FINISHED'} class JCF_OT_set_render_samples(bpy.types.Operator): """Set Cycles Render Samples""" bl_idname = "jcf.set_render_samples" bl_label = "Set Cycles Render Samples" bl_options = {'REGISTER'} samples: bpy.props.FloatProperty(default=128.0) def execute(self, context): bpy.context.scene.cycles.samples = self.samples return {'FINISHED'} class JCF_OT_add_tetrasphere(bpy.types.Operator): """Create a subdivided tetrahedron sphere""" bl_idname = "jcf.add_tetrasphere" bl_label = "Tetrasphere" bl_options = {'REGISTER'} def execute(self, context): """ create solid auto smooth: 30deg shade smooth Subdiv - levels: 4, render levels: 4, quality: 6, use limit surface: True Cast - type: sphere, factor: 1, size: 1, use radius as size: False -- Apply -- Add vertex groups: Cuts, Rim, Shell Assign interleaved branches to cuts Mask - vertex group: cuts inverted, threshold: 0.999 Subdiv - levels: 3, render levels: 3, quality: 6, use limit surface: True Cast - type: sphere, factor: 1, size: 1, use radius as size: False Solidify - thickness: 10cm, offset: -1, even thickness: True, rim fill: True, high quality normals: true, vertex groups: shell/rim Bevel - edges, type: offset, amount: 1cm, segments: 1, limit method: angle, angle: 30deg, harden normals: true Bevel - edges, type: offset, amount: 1mm, segments: 1, limit method: angle, angle: 30deg, harden normals: true """ bpy.ops.mesh.primitive_solid_add() ao = bpy.context.active_object if ao: subsurf = ao.modifiers.new(name="Subdivision", type='SUBSURF') subsurf.levels = 3 subsurf.render_levels = 3 subsurf.quality = 6 subsurf.use_limit_surface = True subsurf.show_only_control_edges = False cast = ao.modifiers.new(name="Cast", type='CAST') cast.factor = 1 cast.size = 1 cast.use_radius_as_size = False return {'FINISHED'}
{"/panels.py": ["/__init__.py"], "/operators.py": ["/__init__.py"], "/__init__.py": ["/panels.py", "/operators.py"]}
69,954
jocafa/JCF_Shortcuts
refs/heads/main
/constants.py
import bpy resolutions = [ { "name": "720p", "width": 1280.0, "height": 720.0 }, { "name": "1080p", "width": 1920.0, "height": 1080.0 }, { "name": "WQHD", "width": 2560.0, "height": 1440.0 }, { "name": "UHD", "width": 3840.0, "height": 2160.0 }, { "name": "256²", "width": 256.0, "height": 256.0 }, { "name": "1024²", "width": 1024.0, "height": 1024.0 } ] scales = [ ["¼", 1/4], ["½", 1/2], ["1", 1], ["2", 2], ["4", 4] ] # ⁰¹²³⁴⁵⁶⁷⁸⁹ samples = [ {"name": "4", "value": 16.0}, {"name": "5", "value": 32.0}, {"name": "6", "value": 64.0}, {"name": "7", "value": 128.0}, {"name": "8", "value": 256.0}, {"name": "9", "value": 512.0}, {"name": "10", "value": 1024.0}, {"name": "11", "value": 2048.0}, {"name": "12", "value": 4096.0}, {"name": "13", "value": 8192.0}, {"name": "14", "value": 16384.0}, {"name": "15", "value": 32768.0}, {"name": "16", "value": 65536.0}, {"name": "24", "value": 16777216.0} ]
{"/panels.py": ["/__init__.py"], "/operators.py": ["/__init__.py"], "/__init__.py": ["/panels.py", "/operators.py"]}
69,955
jocafa/JCF_Shortcuts
refs/heads/main
/__init__.py
bl_info = { "name": "Jocafa Shortcuts", "description": "Jocafa's Shortcuts", "author": "Josh Faul", "version": (0, 0, 1), "blender": (2, 90, 0), "location": "3D View > Sidebar", "warning": "", "category": "3D View" } import bpy #import panels from .panels import ( JCF_ShortcutsPanel, JCF_RenderShortcutsPanel ) #import operators from .operators import ( JCF_OT_set_render_size, JCF_OT_set_render_scale, JCF_OT_set_render_samples, JCF_OT_add_tetrasphere, JCF_OT_debug ) #shared properties class JCF_Properties(bpy.types.PropertyGroup): """JCF Shared Properties""" overlays_expanded: bpy.props.BoolProperty(default=True) foo: bpy.props.FloatProperty(name="foo", default=0.0, min=0.0, max=1.0) classes = ( JCF_Properties, JCF_ShortcutsPanel, JCF_RenderShortcutsPanel, JCF_OT_set_render_size, JCF_OT_set_render_scale, JCF_OT_set_render_samples, JCF_OT_add_tetrasphere, JCF_OT_debug ) def register(): for cls in classes: bpy.utils.register_class(cls) bpy.types.Scene.jcf_props = bpy.props.PointerProperty(type=JCF_Properties) def unregister(): for cls in classes: bpy.utils.unregister_class(cls) del bpy.types.Scene.jcf_props if __name__ == "__main__": register()
{"/panels.py": ["/__init__.py"], "/operators.py": ["/__init__.py"], "/__init__.py": ["/panels.py", "/operators.py"]}
69,995
DableUTeeF/RLGames
refs/heads/master
/ai/composite/keras/CompositeNNet.py
from keras.models import * from keras.layers import * from keras.optimizers import * # TPU_WORKER = 'grpc://' + os.environ['COLAB_TPU_ADDR'] class CompositeNNet: def __init__(self, game, args): # game params try: self.board_x, self.board_y = game.getBoardSize() except AttributeError: self.board_x, self.board_y = game[0].getBoardSize() try: self.action_size = [game[0].getActionSize(), game[1].getActionSize()] except TypeError: self.action_size = game.getActionSize() self.args = args # Neural Net self.input_boards = Input(shape=(self.board_x, self.board_y)) x = Reshape((self.board_x, self.board_y, 1))(self.input_boards) x = self.conv_block(x, 256) for _ in range(8): x = self.res_block(x, 256) self.c4pi = self.policy_head(x, self.action_size[0]) self.c4v = self.value_head(x) self.c4model = Model(inputs=self.input_boards, outputs=[self.c4pi, self.c4v]) self.c4model.compile(loss=['categorical_crossentropy', 'mean_squared_error'], optimizer=Adam(args.lr)) # self.c4model = tf.contrib.tpu.keras_to_tpu_model( # self.c4model, # strategy=tf.contrib.tpu.TPUDistributionStrategy( # tf.contrib.cluster_resolver.TPUClusterResolver(TPU_WORKER))) self.othpi = self.policy_head(x, self.action_size[1]) self.othv = self.value_head(x) self.othmodel = Model(inputs=self.input_boards, outputs=[self.othpi, self.othv]) self.othmodel.compile(loss=['categorical_crossentropy', 'mean_squared_error'], optimizer=Adam(args.lr)) # self.othmodel = tf.contrib.tpu.keras_to_tpu_model( # self.othmodel, # strategy=tf.contrib.tpu.TPUDistributionStrategy( # tf.contrib.cluster_resolver.TPUClusterResolver(TPU_WORKER))) self.model = [self.c4model, self.othmodel] def conv_block(self, x, kernel): x = Conv2D(kernel, 3, padding='same', use_bias=False, trainable=self.args.train)(x) x = BatchNormalization()(x) x = Activation('relu')(x) return x def res_block(self, inp, kernel): x = Conv2D(kernel, 3, padding='same', use_bias=False, trainable=self.args.train)(inp) x = BatchNormalization()(x) x = Activation('relu')(x) x = Conv2D(kernel, 3, padding='same', use_bias=False, trainable=self.args.train)(x) x = BatchNormalization()(x) x = Add()([inp, x]) x = Activation('relu')(x) return x @staticmethod def policy_head(x, action_size): x = Conv2D(2, 1, use_bias=False)(x) x = BatchNormalization()(x) x = Activation('relu')(x) x = Flatten()(x) x = Dropout(0.5)(x) x = Dense(action_size, activation='softmax', name='pi')(x) return x @staticmethod def value_head(x): x = Conv2D(1, 1, use_bias=False)(x) x = BatchNormalization()(x) x = Activation('relu')(x) x = Flatten()(x) x = Dropout(0.5)(x) x = Dense(256, use_bias=False)(x) x = BatchNormalization()(x) x = Activation('relu')(x) x = Dropout(0.5)(x) x = Dense(1, activation='tanh', name='v')(x) return x
{"/ai/composite/keras/NNet.py": ["/ai/composite/keras/CompositeNNet.py"], "/mainscreen.py": ["/mainwindow.py", "/newgame.py"], "/main.py": ["/mainscreen.py"]}
69,996
DableUTeeF/RLGames
refs/heads/master
/ai/composite/keras/NNet.py
import os import numpy as np import sys import tensorflow as tf sys.path.append('..') from ...utils import * from .CompositeNNet import CompositeNNet as Cnnet args = dotdict({ 'lr': 0.0001, 'dropout': 0.3, 'epochs': 1, 'batch_size': 1024, 'cuda': True, 'num_channels': 512, 'train': False, }) class NNetWrapper: def __init__(self, game): self.graph = tf.get_default_graph() self.nnet = Cnnet(game, args) self.board_x, self.board_y = game.getBoardSize() self.action_size = game.getActionSize() def train(self, examples): """ examples: list of list of examples, each example is of form (board, pi, v) """ a = int(np.round(np.random.rand())) g = ['Connect4', 'Othello'] for _ in range(2): print(f'training {g[a]}') input_boards, target_pis, target_vs = list(zip(*examples[a])) input_boards = np.asarray(input_boards) target_pis = np.asarray(target_pis) target_vs = np.asarray(target_vs) self.nnet.model[a].fit(x=input_boards, y=[target_pis, target_vs], batch_size=args.batch_size, epochs=args.epochs) a = ~a def predict(self, board, gindex): """ board: np array with board """ # timing # start = time.time() # preparing input board = board[np.newaxis, :, :] with self.graph.as_default(): # run self.nnet.model[gindex]._make_predict_function() pi, v = self.nnet.model[gindex].predict(board) return pi[0], v[0] def save_checkpoint(self, folder='checkpoint', filename='checkpoint.pth.tar'): for i in range(2): filepath = os.path.join(folder, str(i)+filename) if not os.path.exists(folder): print("Checkpoint Directory does not exist! Making directory {}".format(folder)) os.mkdir(folder) else: pass self.nnet.model[i].save_weights(filepath) def load_checkpoint(self, folder='checkpoint', filename='checkpoint.pth.tar'): for i in range(2): filepath = os.path.join(folder, str(i)+filename) if not os.path.exists(filepath): raise ("No model in path {}".format(filepath)) self.nnet.model[i].load_weights(filepath)
{"/ai/composite/keras/NNet.py": ["/ai/composite/keras/CompositeNNet.py"], "/mainscreen.py": ["/mainwindow.py", "/newgame.py"], "/main.py": ["/mainscreen.py"]}
69,997
DableUTeeF/RLGames
refs/heads/master
/aicompare.py
import os os.environ["CUDA_VISIBLE_DEVICES"] = "2" from ai.Arena import Arena from ai.MCTS import MCTS from ai.utils import dotdict from ai.othello.OthelloGame import OthelloGame as Game from ai.othello.keras.NNet import NNetWrapper as nn import numpy as np if __name__ == '__main__': args = dotdict({'numMCTSSims': 25, 'cpuct': .1, 'arenaCompare': 2, }) # ckpt_o = [41, 43] ckpt_o = [22, 34] ckpt_c = [17, 34] result = [] g = Game(8) normalnet = nn(g) for o in ckpt_o: for c in ckpt_c: normalnet.load_checkpoint('ai/weights', f'othello_8x8x{o}.pth.tar') # c4net.load_checkpoint('ai/weights', 'othello_8x8x73_best.pth.tar') compositenet = nn(g) compositenet.load_checkpoint('ai/weights', f'othello_c4_8x8x{c}.pth.tar') c4mcts = MCTS(g, normalnet, args) nmcts = MCTS(g, compositenet, args) arena = Arena(lambda x: np.argmax(c4mcts.getActionProb(x, temp=0)), lambda x: np.argmax(nmcts.getActionProb(x, temp=0)), g) normalwins, compositewins, draws = arena.playGames(args.arenaCompare) result.append((normalwins, compositewins, draws)) print(f'\nNorm wins: {normalwins}') print(f'c4 wins: {compositewins}') print(f'draws: {draws}') with open('compare_c4_o1.txt', 'w') as wr: wr.write(str(result))
{"/ai/composite/keras/NNet.py": ["/ai/composite/keras/CompositeNNet.py"], "/mainscreen.py": ["/mainwindow.py", "/newgame.py"], "/main.py": ["/mainscreen.py"]}
69,998
DableUTeeF/RLGames
refs/heads/master
/modelrecon.py
from keras.models import * from keras.layers import * from keras.optimizers import * def createmodel(size): input_boards = Input(shape=(size, size)) x = Reshape((size, size, 1))(input_boards) x = conv_block(x, 256, 1) for _ in range(4): x = res_block(x, 256, _+2) pi = policy_head(size*size+1, x) v = value_head(x) model = Model(inputs=input_boards, outputs=[pi, v]) # model.compile(loss=['categorical_crossentropy', 'mean_squared_error'], optimizer=Adam(1e-4)) return model def conv_block(x, kernel, block_id): x = Conv2D(kernel, 3, padding='same', use_bias=False, name=f'block{block_id}_conv')(x) x = BatchNormalization(name=f'block{block_id}_bn')(x) x = Activation('relu', name=f'block{block_id}_relu')(x) return x def res_block(inp, kernel, block_id): x = Conv2D(kernel, 3, padding='same', use_bias=False, name=f'block{block_id}_conv1')(inp) x = BatchNormalization(name=f'block{block_id}_bn1')(x) x = Activation('relu', name=f'block{block_id}_relu1')(x) x = Conv2D(kernel, 3, padding='same', use_bias=False, name=f'block{block_id}_conv2')(x) x = BatchNormalization(name=f'block{block_id}_bn2')(x) x = Add(name=f'block{block_id}_add')([inp, x]) x = Activation('relu', name=f'block{block_id}_relu2')(x) return x def policy_head(action_size, x): x = Conv2D(2, 1, use_bias=False, name='policy_conv')(x) x = BatchNormalization(name='policy_bn')(x) x = Activation('relu', name='policy_relu')(x) x = Flatten(name='policy_flatten')(x) x = Dropout(0.5, name='policy_dropout')(x) x = Dense(action_size, activation='softmax', name='pi')(x) return x def value_head(x): x = Conv2D(1, 1, use_bias=False, name='value_conv1')(x) x = BatchNormalization(name='value_bn1')(x) x = Activation('relu', name='value_relu1')(x) x = Flatten(name='value_flatten')(x) x = Dropout(0.5, name='value_dropout1')(x) x = Dense(256, use_bias=False, name='value_dense')(x) x = BatchNormalization(name='value_bn2')(x) x = Activation('relu', name='value_relu2')(x) x = Dropout(0.5, name='value_dropout2')(x) x = Dense(1, activation='tanh', name='v')(x) return x if __name__ == '__main__': # Neural Net model8 = createmodel(8) model8.trainable = False model8.load_weights('ai/weights/othello_8x8x73_best.pth.tar') xs = model8.get_layer('block5_relu2').output pis = policy_head(8, xs) vs = value_head(xs) model10 = Model(model8.input, outputs=[pis, vs]) print(model10.summary()) model10.save_weights('ai/weights/connect4o.h5')
{"/ai/composite/keras/NNet.py": ["/ai/composite/keras/CompositeNNet.py"], "/mainscreen.py": ["/mainwindow.py", "/newgame.py"], "/main.py": ["/mainscreen.py"]}
69,999
DableUTeeF/RLGames
refs/heads/master
/ai/othello/keras/OthelloNNet.py
import sys sys.path.append('..') from ...utils import * import argparse from keras.models import * from keras.layers import * from keras.optimizers import * class OthelloNNet: def __init__(self, game, args): # game params self.board_x, self.board_y = game.getBoardSize() self.action_size = game.getActionSize() self.args = args # Neural Net self.input_boards = Input(shape=(self.board_x, self.board_y)) x = Reshape((self.board_x, self.board_y, 1))(self.input_boards) x = self.conv_block(x, 256) for _ in range(4): x = self.res_block(x, 256) self.pi = self.policy_head(x) self.v = self.value_head(x) self.model = Model(inputs=self.input_boards, outputs=[self.pi, self.v]) self.model.compile(loss=['categorical_crossentropy', 'mean_squared_error'], optimizer=Adam(args.lr)) def conv_block(self, x, kernel): x = Conv2D(kernel, 3, padding='same', use_bias=False, trainable=self.args.train)(x) x = BatchNormalization()(x) x = Activation('relu')(x) return x def res_block(self, inp, kernel): x = Conv2D(kernel, 3, padding='same', use_bias=False, trainable=self.args.train)(inp) x = BatchNormalization()(x) x = Activation('relu')(x) x = Conv2D(kernel, 3, padding='same', use_bias=False, trainable=self.args.train)(x) x = BatchNormalization()(x) x = Add()([inp, x]) x = Activation('relu')(x) return x def policy_head(self, x): x = Conv2D(2, 1, use_bias=False)(x) x = BatchNormalization()(x) x = Activation('relu')(x) x = Flatten()(x) x = Dropout(0.5)(x) x = Dense(self.action_size, activation='softmax', name='pi')(x) return x @staticmethod def value_head(x): x = Conv2D(1, 1, use_bias=False)(x) x = BatchNormalization()(x) x = Activation('relu')(x) x = Flatten()(x) x = Dropout(0.5)(x) x = Dense(256, use_bias=False)(x) x = BatchNormalization()(x) x = Activation('relu')(x) x = Dropout(0.5)(x) x = Dense(1, activation='tanh', name='v')(x) return x
{"/ai/composite/keras/NNet.py": ["/ai/composite/keras/CompositeNNet.py"], "/mainscreen.py": ["/mainwindow.py", "/newgame.py"], "/main.py": ["/mainscreen.py"]}
70,000
DableUTeeF/RLGames
refs/heads/master
/ai/composite/CompositeGame.py
import numpy as np from ..Game import Game from ..connect4.Connect4Game import Connect4Game from ..othello.OthelloGame import OthelloGame class CompositeGame(Game): def __init__(self, size): self.games = [Connect4Game(size, size), OthelloGame(size)] def getActionSize(self): return self.games[0].getActionSize(), self.games[1].getActionSize() def getBoardSize(self): return self.games[0].getBoardSize()
{"/ai/composite/keras/NNet.py": ["/ai/composite/keras/CompositeNNet.py"], "/mainscreen.py": ["/mainwindow.py", "/newgame.py"], "/main.py": ["/mainscreen.py"]}
70,001
DableUTeeF/RLGames
refs/heads/master
/ai/pit.py
from ai import Arena from ai.MCTS import MCTS # from ai.othello.OthelloGame import OthelloGame, display # from ai.othello.OthelloPlayers import * # from ai.othello.keras.NNet import NNetWrapper as NNet from ai.connect4.Connect4Game import Connect4Game, display from ai.connect4.Connect4Players import * from ai.connect4.keras.NNet import NNetWrapper as NNet import numpy as np from ai.utils import * """ use this script to play any two agents against each other, or play manually with any agent. """ g = Connect4Game(8) # all players rp = RandomPlayer(g).play # gp = GreedyConnect4Player(g).play hp = HumanConnect4Player(g).play # nnet players n1 = NNet(g) # n1.load_checkpoint('weights/', '8x8x60_best.pth.tar') args1 = dotdict({'numMCTSSims': 50, 'cpuct': 1.0}) mcts1 = MCTS(g, n1, args1) n1p = lambda x: np.argmax(mcts1.getActionProb(x, temp=0)) arena = Arena.Arena(n1p, hp, g, display=display) print(arena.playGames(2, verbose=True))
{"/ai/composite/keras/NNet.py": ["/ai/composite/keras/CompositeNNet.py"], "/mainscreen.py": ["/mainwindow.py", "/newgame.py"], "/main.py": ["/mainscreen.py"]}
70,002
DableUTeeF/RLGames
refs/heads/master
/mainscreen.py
# -*- coding: utf-8 -*- r""" Behold, removing tf.Session() in the very first line will cause "interrupted by signal 11: SIGSEGV". You need to initiate a Session to reserve GPU's memory for some reason. At least, in my tensorflow 1.4.0. """ import tensorflow as tf; tf.Session() from PyQt5 import QtCore, QtWidgets, QtGui, QtTest, QtSvg from PyQt5.QtCore import pyqtSlot, Qt from PyQt5.QtWidgets import QMainWindow from PyQt5.QtGui import QFont, QImage, QPalette, QBrush from PIL import ImageQt, Image from ai.MCTS import MCTS from ai.othello.OthelloGame import OthelloGame as Og from ai.othello.keras.NNet import NNetWrapper as ONNet import pyscreenshot as screenshot from ai.gobang.GobangGame import GobangGame as Gg from ai.gobang.keras.NNet import NNetWrapper as GNNet from ai.connect4.Connect4Game import Connect4Game as Cg from ai.connect4.keras.NNet import NNetWrapper as CNNet from ai.utils import * from mainwindow import Ui_MainWindow from newgame import Ui_NewGame import time import numpy as np import os import platform # todo: 1.train with c4 weights(in progress) # todo: 2.train with head fixed weights(see testdiffheadandtop) # todo: 3.train from scratch class QMainScreen(QMainWindow): def __init__(self, parent=None): QtWidgets.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.scene = QtWidgets.QGraphicsScene() self.scene.mousePressEvent = self.scene_mousePressEvent self.ui.graphicsViewBoard.setScene(self.scene) self.ui.graphicsViewBoard.setFixedSize(499, 499) self.ui.actionNewGame.triggered.connect(self.startButton_click) self.ui.actionHint.triggered.connect(self.hint_toggle) self.ui.actionAI.triggered.connect(self.ai_toggle) self.ui.blackLcdNumber.setSegmentStyle(QtWidgets.QLCDNumber.Filled) self.ui.whiteLcdNumber.setSegmentStyle(QtWidgets.QLCDNumber.Filled) # self.ui.statusBar.hide() if platform.system() == 'Linux': self.setFixedSize(self.size()) else: self.setFixedSize(600, 625) self.bg = ImageQt.ImageQt(Image.open('img/board2.png')) self.tatami = QImage('img/tatami.png').mirrored() palette = QPalette() # noinspection PyTypeChecker palette.setBrush(10, QBrush(self.tatami)) self.setPalette(palette) self.repaint() self.newgame = QtWidgets.QMdiSubWindow() self.newgamewindow = Ui_NewGame() self.newgamewindow.setupUi(self.newgame) self.newgame.setFixedSize(self.newgame.size()) self.newgamewindow.whichGameBox.currentIndexChanged.connect(self.whichGameChanged) self.newgamewindow.boardSizeBox_h.currentIndexChanged.connect(self.newwindow_boardsize_h) self.newgamewindow.boardSizeBox_w.currentIndexChanged.connect(self.newwindow_boardsize_w) self.newgamewindow.CancelButton.clicked.connect(self.cancelclick) self.newgamewindow.OKButton.clicked.connect(self.startgame) self.initiate_newgame() self.g = Og self.NNet = ONNet self.bsize = {6: [498, 83], 7: [497, 71], 8: [496, 62], 9: [495, 55], 10: [500, 50]} self.recentMove = [0, 0, 0] self.n = 0 self.b = 1 self.w = -1 r"""nnet players""" self.args1 = None self.mcts1 = None self.mctsplayer = None self.AI = True r""" start with black """ self.turn = 1 self.hint = False r""" A game to play and a board """ self.game = self.g(8) self.board = None self.n1 = self.NNet(self.game) r""" Count number of pieces """ self.BLACK = 0 self.WHITE = 0 self.startgame(None) def paintEvent(self, event): painter = QtGui.QPainter(self) f = 0 if platform.system() == 'Linux' else 20 for i in range(1, 8): painter.fillRect(i+40, i+20+f, 520, 520, QtGui.QColor(10, 10, 10, int(40-1.25*i))) painter.fillRect(40, 20+f, 520, 520, QtGui.QColor(209, 143, 55)) def fillshadow(self, x, y, side): for i in range(1, 4): rect = QtCore.QRectF(QtCore.QPointF(x * side-i+9, y * side-i+9), QtCore.QSizeF(side-10, side-10)) self.scene.addEllipse(rect, QtGui.QPen(QtGui.QColor(0, 0, 0, int(30+10*i))), QtGui.QBrush(QtGui.QColor(0, 0, 0, int(30+10*i)))) # -------------------------------- New Game -------------------------------- # def initiate_newgame(self): self.newgamewindow.whichGameBox.clear() self.newgamewindow.whichGameBox.addItem('Othello') self.newgamewindow.whichGameBox.addItem('Connect4') def newwindow_boardsize_h(self, _): if self.newgamewindow.whichGameBox.currentIndex() == 0: self.newgamewindow.boardSizeBox_w.setCurrentIndex(self.newgamewindow.boardSizeBox_h.currentIndex()) def newwindow_boardsize_w(self, _): if self.newgamewindow.whichGameBox.currentIndex() == 0: self.newgamewindow.boardSizeBox_h.setCurrentIndex(self.newgamewindow.boardSizeBox_w.currentIndex()) def whichGameChanged(self, gameidx): # ----- Board size ----- # self.newgamewindow.boardSizeBox_h.clear() self.newgamewindow.boardSizeBox_w.clear() self.newgamewindow.boardSizeBox_h.addItem('6') self.newgamewindow.boardSizeBox_w.addItem('6') if gameidx == 1: self.newgamewindow.boardSizeBox_h.addItem('7') self.newgamewindow.boardSizeBox_w.addItem('7') self.newgamewindow.boardSizeBox_h.addItem('8') self.newgamewindow.boardSizeBox_w.addItem('8') self.newgamewindow.boardSizeBox_h.addItem('10') self.newgamewindow.boardSizeBox_w.addItem('10') self.newgamewindow.boardSizeBox_h.setCurrentIndex(1) self.newgamewindow.boardSizeBox_w.setCurrentIndex(1) # ------ Weights ------ # self.newgamewindow.weightBox.clear() for file in os.listdir('ai/weights'): if self.newgamewindow.whichGameBox.currentIndex() == 0: if file.startswith('othello'): self.newgamewindow.weightBox.addItem(file) elif self.newgamewindow.whichGameBox.currentIndex() == 1: if file.startswith('connect4'): self.newgamewindow.weightBox.addItem(file) def cancelclick(self, _): self.newgame.hide() # ------------------------------ Main Window ------------------------------- # def ai_toggle(self, _): self.AI = not self.AI self.refresh() def updateText(self, ai=None, user=None): bfont = QFont() wfont = QFont() if self.g == Og: self.ui.blackLcdNumber.display(str(self.BLACK)) self.ui.whiteLcdNumber.display(str(self.WHITE)) else: pi, v = self.n1.predict(self.game.getCanonicalForm(self.board, self.b)) self.ui.blackLcdNumber.display(str(int((v+1)*50))) self.ui.whiteLcdNumber.display(str(int(100-((v+1)*50)))) if self.game.getGameEnded(self.board, self.turn): return aipalette = self.ui.whiteLcdNumber.palette() humanpalette = self.ui.blackLcdNumber.palette() # Text aipalette.setColor(aipalette.WindowText, QtGui.QColor(255, 0, 0)) humanpalette.setColor(humanpalette.WindowText, QtGui.QColor(0, 0, 255)) # # "light" border aipalette.setColor(aipalette.Light, QtGui.QColor(255, 85, 85)) humanpalette.setColor(humanpalette.Light, QtGui.QColor(85, 85, 255)) # # "dark" border # aipalette.setColor(aipalette.Dark, QtGui.QColor(150, 60, 60)) # humanpalette.setColor(humanpalette.Dark, QtGui.QColor(60, 60, 150)) self.ui.whiteLcdNumber.setPalette(humanpalette) self.ui.blackLcdNumber.setPalette(aipalette) if ai == -1: self.ui.rightPlayerLabel.setText('AI') self.ui.leftPlayerLabel.setText('Human') elif ai == 1: self.ui.leftPlayerLabel.setText('AI') self.ui.rightPlayerLabel.setText('Human') else: if user: self.ui.rightPlayerLabel.setText(user[1]) self.ui.leftPlayerLabel.setText(user[0]) else: self.ui.rightPlayerLabel.setText('Human') self.ui.leftPlayerLabel.setText('Human') if self.turn == self.b: bfont.setBold(True) bfont.setUnderline(True) self.ui.blackLabel.setFont(bfont) self.ui.whiteLabel.setFont(wfont) else: wfont.setBold(True) wfont.setUnderline(True) self.ui.blackLabel.setFont(bfont) self.ui.whiteLabel.setFont(wfont) def hint_toggle(self, _): self.hint = ~self.hint self.refresh() def startButton_click(self, _): self.newgame.show() def startgame(self, _): self.ui.graphicsViewBoard.resize(self.bsize[int(self.newgamewindow.boardSizeBox_w.currentText())][0], self.bsize[int(self.newgamewindow.boardSizeBox_h.currentText())][0]) if self.newgamewindow.whichGameBox.currentIndex() == 0: self.g = Og self.NNet = ONNet self.game = self.g(int(self.newgamewindow.boardSizeBox_h.currentText())) self.n1 = self.NNet(self.game) elif self.newgamewindow.whichGameBox.currentIndex() == 1: self.g = Cg self.NNet = CNNet self.game = self.g(int(self.newgamewindow.boardSizeBox_h.currentText()), int(self.newgamewindow.boardSizeBox_w.currentText())) self.n1 = self.NNet(self.game) weights = self.newgamewindow.weightBox.currentText() self.turn = 1 self.board = self.game.getInitBoard() try: self.n1.load_checkpoint('ai/weights/', weights) except: print('Cannot load weights') try: nsims = int(self.newgamewindow.mctsSimsBox.value()) self.args1 = dotdict({'numMCTSSims': nsims, 'cpuct': 1.0}) except ValueError: self.args1 = dotdict({'numMCTSSims': 25, 'cpuct': 1.0}) self.mcts1 = MCTS(self.game, self.n1, self.args1) self.mctsplayer = lambda x: np.argmax(self.mcts1.getActionProb(x, temp=0)) self.refresh() if self.newgamewindow.aiTurnBox.isChecked(): self.aimove() self.newgame.hide() self.updateText(ai=-self.turn) def mouseReleaseEvent(self, a0: QtGui.QMouseEvent): self.update() # noinspection PyArgumentList def scene_mousePressEvent(self, event): sidex = self.bsize[int(self.newgamewindow.boardSizeBox_w.currentText())][1] sidey = self.bsize[int(self.newgamewindow.boardSizeBox_h.currentText())][1] # self.auto() x = int(event.scenePos().x() // sidex) y = int(event.scenePos().y() // sidey) if self.g == Og or self.g == Gg: action = y * int(self.newgamewindow.boardSizeBox_w.currentText()) + x else: action = x valid = self.game.getValidMoves(self.board, self.turn) if valid[action] == 0: return self.board, self.turn = self.game.getNextState(self.board, self.turn, action) self.recentMove = [x, y, self.turn] self.refresh() self.updateText(self.turn) if self.ui.actionAI.isChecked() and self.game.getGameEnded(self.board, self.turn) == 0: QtTest.QTest.qWait(200) while True: self.aimove() valid = self.game.getValidMoves(self.board, self.turn) if np.sum(valid[:-1]) > 0 or self.game.getGameEnded(self.board, self.turn) != 0: break else: self.turn *= -1 QtTest.QTest.qWait(600) def auto(self): sidex = self.bsize[int(self.newgamewindow.boardSizeBox_w.currentText())][1] sidey = self.bsize[int(self.newgamewindow.boardSizeBox_h.currentText())][1] names = ['N22-C17', 'C17-N22', 'N34-C17', 'C17-N34', 'N22-C34', 'C34-N22', 'N34-C34', 'C34-N34'] for idx, iteration in enumerate(names): os.mkdir(f'cap_3/{iteration}') ls = eval(open(f'moves_3/{idx+8}.txt', 'r').read()) self.startgame(None) for i, action in enumerate(ls): action = int(action) self.board, self.turn = self.game.getNextState(self.board, self.turn, action) x = action % 8 y = action // 8 sr = QtCore.QRectF(QtCore.QPointF(x * sidex + (sidex/2)-7, y * sidey + (sidey/2) - 7), QtCore.QSizeF(14, 14)) self.refresh() self.scene.addEllipse(sr, QtGui.QPen(QtCore.Qt.darkBlue), QtGui.QBrush(QtCore.Qt.blue)) self.updateText(None, iteration.split('-')) QtTest.QTest.qWait(200) # im = self.grab() im.save(f'cap_3/{iteration}/{i}.jpg') # def aimove(self): action = self.mctsplayer(self.game.getCanonicalForm(self.board, self.turn)) self.board, self.turn = self.game.getNextState(self.board, self.turn, action) self.recentMove = [action % int(self.newgamewindow.boardSizeBox_w.currentText()), action // int(self.newgamewindow.boardSizeBox_h.currentText()), self.turn] self.refresh() self.updateText(-self.turn) def refresh(self): self.scene.clear() pend = QtGui.QPen(QtGui.QColor(94, 46, 12)) penl = QtGui.QPen(QtGui.QColor(209, 143, 55)) pixMap = QtGui.QPixmap.fromImage(self.bg) self.scene.addPixmap(pixMap) sidex = self.bsize[int(self.newgamewindow.boardSizeBox_w.currentText())][1] sidey = self.bsize[int(self.newgamewindow.boardSizeBox_h.currentText())][1] self.WHITE = 0 self.BLACK = 0 for y in range(int(self.newgamewindow.boardSizeBox_h.currentText())): for x in range(int(self.newgamewindow.boardSizeBox_w.currentText())): if self.g == Og or self.g == Gg: action = y * int(self.newgamewindow.boardSizeBox_h.currentText()) + x else: action = x valid = self.game.getValidMoves(self.board, self.turn) rd = QtCore.QRectF(QtCore.QPointF(x * sidex, y * sidey), QtCore.QSizeF(sidex, sidey)) rl = QtCore.QRectF(QtCore.QPointF(x * sidex+1, y * sidey+1), QtCore.QSizeF(sidex, sidey)) sr = QtCore.QRectF(QtCore.QPointF(x * sidex + (sidex/2)-7, y * sidey + (sidey/2) - 7), QtCore.QSizeF(14, 14)) self.scene.addRect(rd, pend) self.scene.addRect(rl, penl) if self.board[y][x] == self.b: # self.fillshadow(x, y, side) stone = QtSvg.QGraphicsSvgItem('img/stone_1.svg') stone.setPos(x * sidex + 5, y * sidey + 5) stone.setScale((min(sidex, sidey)-10)/43) self.scene.addItem(stone) self.BLACK += 1 # if [x, y, self.turn] == self.recentMove: # self.scene.addEllipse(sr, QtGui.QPen(QtCore.Qt.white), QtGui.QBrush(QtCore.Qt.white)) elif self.board[y][x] == self.w: # self.fillshadow(x, y, side) # print(x * sidex + 5, y * sidey + 5) # print(x, y) stone = QtSvg.QGraphicsSvgItem('img/stone_-1.svg') stone.setPos(x * sidex + 5, y * sidey + 5) stone.setScale((min(sidex, sidey)-10)/43) self.scene.addItem(stone) self.WHITE += 1 # if [x, y, self.turn] == self.recentMove: # self.scene.addEllipse(sr, QtGui.QPen(QtCore.Qt.black), QtGui.QBrush(QtCore.Qt.black)) elif valid[action] == 1 and self.hint: if self.newgamewindow.aiTurnBox.isChecked() or self.AI: stone = QtSvg.QGraphicsSvgItem('img/stone_h0.svg') elif self.turn == self.w: stone = QtSvg.QGraphicsSvgItem('img/stone_h-1.svg') else: stone = QtSvg.QGraphicsSvgItem('img/stone_h1.svg') stone.setPos(x * sidex + 20, y * sidey + 20) stone.setScale(22/43) self.scene.addItem(stone) self.update()
{"/ai/composite/keras/NNet.py": ["/ai/composite/keras/CompositeNNet.py"], "/mainscreen.py": ["/mainwindow.py", "/newgame.py"], "/main.py": ["/mainscreen.py"]}
70,003
DableUTeeF/RLGames
refs/heads/master
/ai/connect4/keras/Connect4NNet.py
import sys sys.path.append('..') from ...utils import * import argparse from keras.models import * from keras.layers import * from keras.optimizers import * class Connect4NNet: def __init__(self, game, args): # game params self.board_x, self.board_y = game.getBoardSize() self.action_size = game.getActionSize() self.args = args # Neural Net self.input_boards = Input(shape=(self.board_x, self.board_y)) x = Reshape((self.board_x, self.board_y, 1))(self.input_boards) x = self.conv_block(x, 256) for _ in range(8): x = self.res_block(x, 256) self.pi = self.policy_head(x) self.v = self.value_head(x) self.model = Model(inputs=self.input_boards, outputs=[self.pi, self.v]) self.model.compile(loss=['categorical_crossentropy', 'mean_squared_error'], optimizer=Adam(args.lr)) @staticmethod def conv2d_bn(x, filters, num_row, num_col, padding='same', strides=(1, 1), name=None): if name is not None: bn_name = name + '_bn' conv_name = name + '_conv' else: bn_name = None conv_name = None if K.image_data_format() == 'channels_first': bn_axis = 1 else: bn_axis = 3 x = Conv2D( filters, (num_row, num_col), strides=strides, padding=padding, use_bias=False, name=conv_name)(x) x = BatchNormalization(axis=bn_axis, scale=False, name=bn_name)(x) x = Activation('relu', name=name)(x) return x def inception_block(self, x, kernel): branch1x1 = self.conv2d_bn(x, kernel, 1, 1) branch5x5 = self.conv2d_bn(x, kernel * 2 // 3, 1, 1) branch5x5 = self.conv2d_bn(branch5x5, kernel, 5, 5) branch3x3dbl = self.conv2d_bn(x, kernel, 1, 1) branch3x3dbl = self.conv2d_bn(branch3x3dbl, kernel * 3 // 2, 3, 3) branch3x3dbl = self.conv2d_bn(branch3x3dbl, kernel * 3 // 2, 3, 3) branch_pool = AveragePooling2D((3, 3), strides=(1, 1), padding='same')(x) branch_pool = self.conv2d_bn(branch_pool, 32, 1, 1) x = add([x, concatenate( [branch1x1, branch5x5, branch3x3dbl, branch_pool])]) return x def inception_res_block(self, x, kernel): branch1x1 = self.conv2d_bn(x, kernel, 1, 1) branch5x5 = self.conv2d_bn(x, kernel * 2 // 3, 1, 1) branch5x5 = self.conv2d_bn(branch5x5, kernel, 5, 5) branch3x3dbl = self.conv2d_bn(x, kernel, 1, 1) branch3x3dbl = self.conv2d_bn(branch3x3dbl, kernel * 3 // 2, 3, 3) branch3x3dbl = self.conv2d_bn(branch3x3dbl, kernel * 3 // 2, 3, 3) branch_pool = AveragePooling2D((3, 3), strides=(1, 1), padding='same')(x) branch_pool = self.conv2d_bn(branch_pool, 32, 1, 1) x = concatenate( [branch1x1, branch5x5, branch3x3dbl, branch_pool], name='mixed0') return x def conv_block(self, x, kernel): x = Conv2D(kernel, 3, padding='same', use_bias=False, trainable=self.args.train)(x) x = BatchNormalization()(x) x = Activation('relu')(x) return x def res_block(self, inp, kernel): x = Conv2D(kernel, 3, padding='same', use_bias=False, trainable=self.args.train)(inp) x = BatchNormalization()(x) x = Activation('relu')(x) x = Conv2D(kernel, 3, padding='same', use_bias=False, trainable=self.args.train)(x) x = BatchNormalization()(x) x = Add()([inp, x]) x = Activation('relu')(x) return x def policy_head(self, x): x = Conv2D(2, 1, use_bias=False)(x) x = BatchNormalization()(x) x = Activation('relu')(x) x = Flatten()(x) x = Dropout(0.5)(x) x = Dense(self.action_size, activation='softmax', name='pi')(x) return x @staticmethod def value_head(x): x = Conv2D(1, 1, use_bias=False)(x) x = BatchNormalization()(x) x = Activation('relu')(x) x = Flatten()(x) x = Dropout(0.5)(x) x = Dense(256, use_bias=False)(x) x = BatchNormalization()(x) x = Activation('relu')(x) x = Dropout(0.5)(x) x = Dense(1, activation='tanh', name='v')(x) return x
{"/ai/composite/keras/NNet.py": ["/ai/composite/keras/CompositeNNet.py"], "/mainscreen.py": ["/mainwindow.py", "/newgame.py"], "/main.py": ["/mainscreen.py"]}
70,004
DableUTeeF/RLGames
refs/heads/master
/newgame.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/newgame.ui' # # Created by: PyQt5 UI code generator 5.10.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_NewGame(object): def setupUi(self, NewGame): NewGame.setObjectName("NewGame") NewGame.resize(300, 390) NewGame.setMinimumSize(QtCore.QSize(300, 390)) NewGame.setMaximumSize(QtCore.QSize(300, 390)) self.MainFrame = QtWidgets.QFrame(NewGame) self.MainFrame.setGeometry(QtCore.QRect(0, 0, 301, 391)) self.MainFrame.setMinimumSize(QtCore.QSize(301, 391)) self.MainFrame.setMaximumSize(QtCore.QSize(301, 391)) self.MainFrame.setFrameShape(QtWidgets.QFrame.StyledPanel) self.MainFrame.setFrameShadow(QtWidgets.QFrame.Raised) self.MainFrame.setObjectName("MainFrame") self.DecissionButtonsFrame = QtWidgets.QFrame(self.MainFrame) self.DecissionButtonsFrame.setGeometry(QtCore.QRect(100, 330, 171, 41)) self.DecissionButtonsFrame.setFrameShape(QtWidgets.QFrame.StyledPanel) self.DecissionButtonsFrame.setFrameShadow(QtWidgets.QFrame.Raised) self.DecissionButtonsFrame.setObjectName("DecissionButtonsFrame") self.OKButton = QtWidgets.QPushButton(self.DecissionButtonsFrame) self.OKButton.setGeometry(QtCore.QRect(10, 10, 51, 25)) self.OKButton.setObjectName("OKButton") self.CancelButton = QtWidgets.QPushButton(self.DecissionButtonsFrame) self.CancelButton.setGeometry(QtCore.QRect(70, 10, 89, 25)) self.CancelButton.setObjectName("CancelButton") self.ObjectFrame = QtWidgets.QFrame(self.MainFrame) self.ObjectFrame.setGeometry(QtCore.QRect(30, 30, 241, 291)) self.ObjectFrame.setFrameShape(QtWidgets.QFrame.StyledPanel) self.ObjectFrame.setFrameShadow(QtWidgets.QFrame.Raised) self.ObjectFrame.setObjectName("ObjectFrame") self.whichGameLabel = QtWidgets.QLabel(self.ObjectFrame) self.whichGameLabel.setGeometry(QtCore.QRect(20, 40, 67, 17)) self.whichGameLabel.setObjectName("whichGameLabel") self.whichGameBox = QtWidgets.QComboBox(self.ObjectFrame) self.whichGameBox.setGeometry(QtCore.QRect(120, 40, 91, 25)) self.whichGameBox.setObjectName("whichGameBox") self.boardSizeLabel = QtWidgets.QLabel(self.ObjectFrame) self.boardSizeLabel.setGeometry(QtCore.QRect(20, 90, 67, 17)) self.boardSizeLabel.setObjectName("boardSizeLabel") self.boardSizeBox_w = QtWidgets.QComboBox(self.ObjectFrame) self.boardSizeBox_w.setGeometry(QtCore.QRect(120, 90, 41, 25)) self.boardSizeBox_w.setObjectName("boardSizeBox_w") self.mctsSimsLabel = QtWidgets.QLabel(self.ObjectFrame) self.mctsSimsLabel.setGeometry(QtCore.QRect(20, 140, 71, 17)) self.mctsSimsLabel.setObjectName("mctsSimsLabel") self.weightLabel = QtWidgets.QLabel(self.ObjectFrame) self.weightLabel.setGeometry(QtCore.QRect(20, 190, 67, 17)) self.weightLabel.setObjectName("weightLabel") self.weightBox = QtWidgets.QComboBox(self.ObjectFrame) self.weightBox.setGeometry(QtCore.QRect(120, 190, 91, 25)) self.weightBox.setObjectName("weightBox") self.aiTurnLabel = QtWidgets.QLabel(self.ObjectFrame) self.aiTurnLabel.setGeometry(QtCore.QRect(20, 240, 67, 17)) self.aiTurnLabel.setObjectName("aiTurnLabel") self.aiTurnBox = QtWidgets.QCheckBox(self.ObjectFrame) self.aiTurnBox.setGeometry(QtCore.QRect(120, 240, 92, 23)) self.aiTurnBox.setText("") self.aiTurnBox.setObjectName("aiTurnBox") self.mctsSimsBox = QtWidgets.QSpinBox(self.ObjectFrame) self.mctsSimsBox.setGeometry(QtCore.QRect(120, 140, 48, 26)) self.mctsSimsBox.setMinimum(2) self.mctsSimsBox.setMaximum(100) self.mctsSimsBox.setProperty("value", 25) self.mctsSimsBox.setObjectName("mctsSimsBox") self.boardSizeBox_h = QtWidgets.QComboBox(self.ObjectFrame) self.boardSizeBox_h.setGeometry(QtCore.QRect(170, 90, 41, 25)) self.boardSizeBox_h.setObjectName("boardSizeBox_h") self.retranslateUi(NewGame) QtCore.QMetaObject.connectSlotsByName(NewGame) def retranslateUi(self, NewGame): _translate = QtCore.QCoreApplication.translate NewGame.setWindowTitle(_translate("NewGame", "New Game")) self.OKButton.setText(_translate("NewGame", "OK")) self.CancelButton.setText(_translate("NewGame", "cancel")) self.whichGameLabel.setText(_translate("NewGame", "game")) self.boardSizeLabel.setText(_translate("NewGame", "boardSize")) self.mctsSimsLabel.setText(_translate("NewGame", "MCTSSims")) self.weightLabel.setText(_translate("NewGame", "weight")) self.aiTurnLabel.setText(_translate("NewGame", "AI first"))
{"/ai/composite/keras/NNet.py": ["/ai/composite/keras/CompositeNNet.py"], "/mainscreen.py": ["/mainwindow.py", "/newgame.py"], "/main.py": ["/mainscreen.py"]}
70,005
DableUTeeF/RLGames
refs/heads/master
/main.py
import sys from PyQt5.QtWidgets import QApplication from mainscreen import QMainScreen if __name__ == '__main__': app = QApplication(sys.argv) window = QMainScreen() window.show() sys.exit(app.exec_())
{"/ai/composite/keras/NNet.py": ["/ai/composite/keras/CompositeNNet.py"], "/mainscreen.py": ["/mainwindow.py", "/newgame.py"], "/main.py": ["/mainscreen.py"]}
70,006
DableUTeeF/RLGames
refs/heads/master
/mainwindow.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/mainwindow.ui' # # Created by: PyQt5 UI code generator 5.10.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.setWindowModality(QtCore.Qt.NonModal) MainWindow.resize(600, 600) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth()) MainWindow.setSizePolicy(sizePolicy) MainWindow.setMaximumSize(QtCore.QSize(16777215, 16777215)) self.centralWidget = QtWidgets.QWidget(MainWindow) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.centralWidget.sizePolicy().hasHeightForWidth()) self.centralWidget.setSizePolicy(sizePolicy) self.centralWidget.setObjectName("centralWidget") self.graphicsViewBoard = QtWidgets.QGraphicsView(self.centralWidget) self.graphicsViewBoard.setGeometry(QtCore.QRect(50, 30, 500, 500)) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Maximum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.graphicsViewBoard.sizePolicy().hasHeightForWidth()) self.graphicsViewBoard.setSizePolicy(sizePolicy) self.graphicsViewBoard.setMaximumSize(QtCore.QSize(1000, 1000)) self.graphicsViewBoard.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.graphicsViewBoard.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.graphicsViewBoard.setObjectName("graphicsViewBoard") self.frame = QtWidgets.QFrame(self.centralWidget) self.frame.setGeometry(QtCore.QRect(50, 550, 501, 45)) self.frame.setFrameShape(QtWidgets.QFrame.NoFrame) self.frame.setFrameShadow(QtWidgets.QFrame.Plain) self.frame.setObjectName("frame") self.whiteLcdNumber = QtWidgets.QLCDNumber(self.frame) self.whiteLcdNumber.setGeometry(QtCore.QRect(400, 0, 40, 40)) self.whiteLcdNumber.setDigitCount(2) self.whiteLcdNumber.setObjectName("whiteLcdNumber") self.whiteLabel = QtWidgets.QLabel(self.frame) self.whiteLabel.setGeometry(QtCore.QRect(450, 10, 41, 23)) self.whiteLabel.setObjectName("whiteLabel") self.blackLabel = QtWidgets.QLabel(self.frame) self.blackLabel.setGeometry(QtCore.QRect(10, 10, 67, 23)) self.blackLabel.setObjectName("blackLabel") self.blackLcdNumber = QtWidgets.QLCDNumber(self.frame) self.blackLcdNumber.setGeometry(QtCore.QRect(50, 0, 40, 40)) self.blackLcdNumber.setDigitCount(2) self.blackLcdNumber.setObjectName("blackLcdNumber") self.rightPlayerLabel = QtWidgets.QLabel(self.frame) self.rightPlayerLabel.setGeometry(QtCore.QRect(330, 10, 60, 23)) self.rightPlayerLabel.setLayoutDirection(QtCore.Qt.RightToLeft) self.rightPlayerLabel.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.rightPlayerLabel.setObjectName("rightPlayerLabel") self.leftPlayerLabel = QtWidgets.QLabel(self.frame) self.leftPlayerLabel.setGeometry(QtCore.QRect(100, 10, 67, 23)) self.leftPlayerLabel.setObjectName("leftPlayerLabel") MainWindow.setCentralWidget(self.centralWidget) self.menuBar = QtWidgets.QMenuBar(MainWindow) self.menuBar.setGeometry(QtCore.QRect(0, 0, 600, 22)) self.menuBar.setMinimumSize(QtCore.QSize(10, 10)) self.menuBar.setObjectName("menuBar") self.menuFile = QtWidgets.QMenu(self.menuBar) self.menuFile.setObjectName("menuFile") MainWindow.setMenuBar(self.menuBar) self.actionNew_Game = QtWidgets.QAction(MainWindow) self.actionNew_Game.setObjectName("actionNew_Game") self.actionNewGame = QtWidgets.QAction(MainWindow) self.actionNewGame.setObjectName("actionNewGame") self.actionAI = QtWidgets.QAction(MainWindow) self.actionAI.setCheckable(True) self.actionAI.setChecked(True) self.actionAI.setObjectName("actionAI") self.actionHint = QtWidgets.QAction(MainWindow) self.actionHint.setCheckable(True) self.actionHint.setChecked(False) self.actionHint.setObjectName("actionHint") self.menuFile.addAction(self.actionNewGame) self.menuFile.addAction(self.actionAI) self.menuFile.addAction(self.actionHint) self.menuBar.addAction(self.menuFile.menuAction()) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "Othello")) self.whiteLabel.setText(_translate("MainWindow", "White")) self.blackLabel.setText(_translate("MainWindow", "Black")) self.rightPlayerLabel.setText(_translate("MainWindow", "AI")) self.leftPlayerLabel.setText(_translate("MainWindow", "Human")) self.menuFile.setTitle(_translate("MainWindow", "File")) self.actionNew_Game.setText(_translate("MainWindow", "New Game")) self.actionNewGame.setText(_translate("MainWindow", "New Game")) self.actionAI.setText(_translate("MainWindow", "AI")) self.actionHint.setText(_translate("MainWindow", "Hint"))
{"/ai/composite/keras/NNet.py": ["/ai/composite/keras/CompositeNNet.py"], "/mainscreen.py": ["/mainwindow.py", "/newgame.py"], "/main.py": ["/mainscreen.py"]}
70,011
Charckle/svetovifprequel
refs/heads/master
/app/secondary_module/forms.py
# Import Form and RecaptchaField (optional) from flask.ext.wtf import Form # , RecaptchaField # Import Form elements such as TextField and BooleanField (optional) from wtforms import TextField, PasswordField # BooleanField # Import Form validators from wtforms.validators import Required, Email, EqualTo # Define the login form (WTForms) class LoginForm(Form): username_or_email = TextField('Username or Email', [Required(message='Forgot your email address?')]) password = PasswordField('Password', [ Required(message='Must provide a password.')]) class RegisterForm(Form): username = TextField('Username', [Required(message='We need a username for your account.')]) email = TextField('Email', [Email(), Required(message='We need an email for your account.')]) password = PasswordField('Password', [ Required(message='Must provide a password.')])
{"/run.py": ["/app/__init__.py"], "/app/main_page_module/controllers.py": ["/app/main_page_module/forms.py", "/app/main_page_module/other.py", "/app/main_page_module/models.py", "/app/main_page_module/argus.py"], "/app/__init__.py": ["/app/main_page_module/controllers.py"], "/app/main_page_module/models.py": ["/app/__init__.py"], "/app/main_page_module/forms.py": ["/app/main_page_module/models.py"]}
70,012
Charckle/svetovifprequel
refs/heads/master
/run.py
# Run a test server. from app import app #app.run() if __name__ == "__main__": app.run() ''' from flask import Flask, render_template, url_for, request, redirect, flash from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config.from_object("config.DevelopmentConfig") db = SQLAlchemy(app) # Sample HTTP error handling @app.errorhandler(404) def not_found(error): return render_template('404.html'), 404 @app.route("/") def index(): return render_template("index.html") @app.route("/add_entry") def add_entry(): return render_template("add_entry.html") if __name__ == "__main__": db.create_all() app.run() '''
{"/run.py": ["/app/__init__.py"], "/app/main_page_module/controllers.py": ["/app/main_page_module/forms.py", "/app/main_page_module/other.py", "/app/main_page_module/models.py", "/app/main_page_module/argus.py"], "/app/__init__.py": ["/app/main_page_module/controllers.py"], "/app/main_page_module/models.py": ["/app/__init__.py"], "/app/main_page_module/forms.py": ["/app/main_page_module/models.py"]}
70,013
Charckle/svetovifprequel
refs/heads/master
/app/main_page_module/controllers.py
# Import flask dependencies from flask import Blueprint, request, render_template, \ flash, g, session, redirect, url_for, jsonify, send_file # Import module forms from app.main_page_module.forms import LoginForm, RegisterForm, EditUserForm, LocationForm, ParkingForm, TagForm, MythForm, MTagForm, ImgForm, IconForm from app.main_page_module.other import remove_https # Import module models (i.e. User) from app.main_page_module.models import user_sql_create, user_sql_login_check, user_sql_get_all, \ user_sql_get_one, user_sql_delete_one, user_sql_update_one, location_create, location_get_one, location_change, parking_create, \ parking_get_all_of_location, parking_get_one, parking_remove, tag_create, tag_get_all_of_location, tag_get_all, loc_tag_get_one, loc_tag_remove, tag_add, tag_get_one, \ loc_tag_get_one_by, location_get_all, location_delete_one, location_get_all_with_tag, myth_create, myth_get_one, mtag_get_all_of_myth, mtag_get_all, myth_change, \ myth_mtag_remove, myth_get_all_with_mtag, mtag_get_one, myth_mtag_get_one, myth_mtag_get_one_by, myth_get_all, mtag_create, mtag_add, myth_delete_one, location_get_all_argus, \ myths_get_all_argus, location_get_numbers, tag_get_numbers, location_get_all_with_tag_for_argus, myth_get_numbers, mtag_get_numbers, myth_get_all_with_mtag_for_argus, \ icon_get_one, location_get_icon_link, location_get_all_where_rating, location_get_all_with_ids, location_get_all_id_with_tag, img_create, img_get_one, img_remove, \ img_get_all_of_location, location_get_all_where, icon_create #import os import re import os import zipfile import io import pathlib from functools import wraps import datetime from app.main_page_module.argus import WSearch # Define the blueprint: 'auth', set its url prefix: app.url/auth main_page_module = Blueprint('main_page_module', __name__, url_prefix='/') #login decorator def login_required(f): @wraps(f) def wrapper(*args, **kwargs): if 'user_id' in session: return f(*args, **kwargs) else: flash("Please login to access the site.", "error") return redirect(url_for("main_page_module.login")) return wrapper #login check def check_login(): if "user_id" not in session: return True # Set the route and accepted methods @main_page_module.route('/', methods=['GET', 'POST']) def index(): locations = location_get_all() tags = tag_get_all() if request.method == "POST": try: rating = int(request.form["rating"].strip()) tag = int(request.form["tag"].strip()) #print(f"rating: {rating}" ) #print(f"tag: {tag}") except: return render_template("main_page_module/index.html", locations=locations, tags=tags) command = "" if rating in [0,1,2,3,4]: command += f" AND locations.rating = {rating} " if tag != 999999: command += f" AND loc_tag.id_tag = {tag} " locations = location_get_all_where(command) return render_template("main_page_module/index.html", locations=locations, tags=tags) @main_page_module.route('/search_results_loc/', methods=['POST']) def search_results_loc(): key = request.form["key"].strip() choosen_tag = request.form["choosen_tag"] locations = None if key == "": asterix = "" else: asterix = "*" search_object = WSearch() locations_from_argus = search_object.index_search_location(key + asterix) if choosen_tag != "choosen_tag": tag_location_ids = location_get_all_with_tag_for_argus(choosen_tag)[0] results = {url_for('main_page_module.view_location', location_id=int(location[0])): [location[1], location[2], url_for('static', filename='icons/' + str(location_get_icon_link(location[0])[0]))] for location in locations_from_argus if (int(location[0]) in tag_location_ids)} else: results = {url_for('main_page_module.view_location', location_id=int(location[0])): [location[1], location[2], url_for('static', filename='icons/' + str(location_get_icon_link(location[0])[0]))] for location in locations_from_argus} return jsonify(results) @main_page_module.route('/search_results_myth/', methods=['POST']) def search_results_myth(): key = request.form["key"].strip() choosen_tag = request.form["choosen_tag"] locations = None if key == "": asterix = "" else: asterix = "*" search_object = WSearch() myths_from_argus = search_object.index_search_myth(key + asterix) if choosen_tag != "choosen_tag": tag_myths_ids = myth_get_all_with_mtag_for_argus(choosen_tag)[0] results = {url_for('main_page_module.view_myth', myth_id=int(myth[0])): [myth[1], myth[2], myth[0]] for myth in myths_from_argus if (int(location[0]) in tag_myths_ids)} else: results = {url_for('main_page_module.view_myth', myth_id=int(myth[0])): [myth[1], myth[2], myth[0]] for myth in myths_from_argus} #print(results) return jsonify(results) @main_page_module.route('/about/', methods=['GET']) def about(): return render_template("main_page_module/about.html") @main_page_module.route('/search_locations/', methods=['GET']) def search_locations(): #if check_login(): return redirect(url_for("main_page_module.login")) all_tags = tag_get_all() location_numbers = location_get_numbers()[0] tag_numbers = tag_get_numbers()[0] return render_template("main_page_module/search_locations.html", all_tags=all_tags, location_numbers=location_numbers, tag_numbers=tag_numbers) @main_page_module.route('/search_myths/', methods=['GET']) def search_myths(): #if check_login(): return redirect(url_for("main_page_module.login")) all_mtags = mtag_get_all() myth_numbers = myth_get_numbers()[0] mtag_numbers = mtag_get_numbers()[0] return render_template("main_page_module/search_myth.html", all_mtags=all_mtags, myth_numbers=myth_numbers, mtag_numbers=mtag_numbers) @main_page_module.route('/all_mtags/') def all_mtags(): mtags = mtag_get_all() return render_template("main_page_module/all_mtags.html", mtags=mtags) @main_page_module.route('/view_mtag/<mtag_id>') def view_mtag(mtag_id): mtag = mtag_get_one(mtag_id) if (mtag is None): flash('Oznaka ne obstaja!', 'error') return redirect(url_for("main_page_module.all_myths")) myths = myth_get_all_with_mtag(mtag_id) return render_template("main_page_module/view_mtag.html", mtag=mtag, myths=myths) @main_page_module.route('/update_myth_search/', methods=['POST']) @login_required def update_myth_search(): if "update" != request.form["update"]: json_response = {"a": "-1"} return jsonify(json_response) json_response = {"a": "OK"} try: myths = myths_get_all_argus() new_index = WSearch() new_index.index_create_myth(myths) return jsonify(json_response) except: json_response = {"a": "-1"} return jsonify(json_response) @main_page_module.route('/update_loc_search/', methods=['POST']) @login_required def update_loc_search(): if "update" != request.form["update"]: json_response = {"a": "-1"} return jsonify(json_response) json_response = {"a": "OK"} try: locations = location_get_all_argus() new_index = WSearch() new_index.index_create_loc(locations) return jsonify(json_response) except: json_response = {"a": "-1"} return jsonify(json_response) @main_page_module.route('/remove_mtag/', methods=['POST']) @login_required def remove_mtag(): myth_mtag_id = request.form["myth_mtag_id"] myth_mtag = myth_mtag_get_one(myth_mtag_id) json_response = {"a": "OK"} if myth_mtag is not None: myth_mtag_remove(myth_mtag_id, myth_mtag[2]) return jsonify(json_response) else: json_response = {"a": "-1"} return jsonify(json_response) @main_page_module.route('/add_mtag/', methods=['POST']) @login_required def add_mtag(): myth = myth_get_one(request.form["myth_id"]) mtag = mtag_get_one(request.form["mtag_id"]) json_response = {"a": "OK"} if (myth is not None) and (mtag is not None): if myth_mtag_get_one_by(myth[0], mtag[0]) is None: mtag_add(myth[0], mtag[0]) return jsonify(json_response) else: json_response = {"a": "KO"} return jsonify(json_response) else: json_response = {"a": "-1"} return jsonify(json_response) @main_page_module.route('/create_mtag/', methods=['POST']) @login_required def create_mtag(): form = TagForm(request.form) myth = myth_get_one(form.id.data) # Verify the sign in form if (form.validate_on_submit()) and (myth is not None): mtag_create(form.name.data, form.id.data) flash('Oznaka uspesno narejena za to Pripovedko!', 'success') return redirect(url_for("main_page_module.edit_myth", myth_id=form.id.data)) for error in form.errors: print(error) flash('No access or the location does not exist!', 'error') return redirect(url_for("main_page_module.index")) @main_page_module.route('/new_myth', methods=['GET', 'POST']) @login_required def new_myth(): # If sign in form is submitted form = MythForm(request.form) # Verify the sign in form if form.validate_on_submit(): myth_id = myth_create(form.name.data, form.desc_s.data, form.desc_l.data, form.coord.data, form.info.data) flash('Pripovedka uspesno narejena!', 'success') return redirect(f"edit_myth/{myth_id}") """ for error in form.errors: print(error) """ return render_template("main_page_module/myths/new_myth.html", form=form) @main_page_module.route('/edit_myth/<myth_id>', methods=['GET', 'POST']) @login_required def edit_myth(myth_id): myth = myth_get_one(myth_id) form_mtag = MTagForm() if myth is None: flash('Nobena pripovedka najdena', 'error') return redirect(url_for("main_page_module.index")) form = MythForm() form.process(id = myth[0], name = myth[1], desc_s = myth[2], desc_l = myth[3], coord = myth[4], info = myth[5]) mtags = mtag_get_all_of_myth(myth_id) all_mtags = mtag_get_all() return render_template("main_page_module/myths/edit_myth.html", form=form, form_mtag=form_mtag, mtags=mtags, all_mtags=all_mtags) @main_page_module.route('/view_myth/<myth_id>', methods=['GET', 'POST']) def view_myth(myth_id): myth = myth_get_one(myth_id) mtags = mtag_get_all_of_myth(myth_id) if myth is None: flash('Nobene Pripovedke ne najdemo', 'error') return redirect(url_for("main_page_module.index")) return render_template("main_page_module/myths/view_myth.html", myth=myth, mtags=mtags) @main_page_module.route('/change_myth/', methods=['POST']) @login_required def change_myth(): form = MythForm(request.form) myth_id = form.id.data myth = myth_get_one(myth_id) if form.validate_on_submit(): if myth is None: flash('Nobena pripovedka najdena', 'error') return redirect(url_for("main_page_module.index")) myth_change(myth_id, form.name.data, form.desc_s.data, form.desc_l.data, form.coord.data, form.info.data) flash('Pripovedka uspesno spremenjena!', 'success') return redirect(url_for("main_page_module.edit_myth", myth_id=myth_id)) flash('Invalid Data', 'error') for error in form.errors: print(error) return redirect(url_for("main_page_module.index")) @main_page_module.route('/delete_myth/', methods=['POST']) @login_required def delete_myth(): myth_id = request.form["id"] myth = myth_get_one(myth_id) # Verify the sign in form if (myth is not None): #get all mtags of the mzth, to delete them mtags = mtag_get_all_of_myth(myth_id) for mtag in mtags: myth_mtag_remove(mtag[0], mtag[2]) myth_delete_one(myth_id) flash('Pripovedka uspesno izbrisana!', 'success') return redirect(url_for("main_page_module.all_myths")) flash('No access or the location does not exist!', 'error') return redirect(url_for("main_page_module.all_myths")) @main_page_module.route('/all_myths/') def all_myths(): myths = myth_get_all() return render_template("main_page_module/myths/all_myths.html", myths=myths) @main_page_module.route('/all_locations/') def all_locations(): locations = location_get_all() return render_template("main_page_module/locations/all_locations.html", locations=locations) @main_page_module.route('/delete_location/', methods=['POST']) @login_required def delete_location(): location_id = request.form["id"] location = location_get_one(location_id) # Verify the sign in form if (location is not None): #get all tags of the location, to delete them tags_querry = tag_get_all_of_location(location_id) for tag in tags_querry: loc_tag_remove(tag[0], tag[2]) location_delete_one(location_id) flash('Location successfully deleted!', 'success') return redirect(url_for("main_page_module.all_locations")) flash('No access or the location does not exist!', 'error') return redirect(url_for("main_page_module.all_locations")) @main_page_module.route('/all_tags/') def all_tags(): tags = tag_get_all() return render_template("main_page_module/all_tags.html", tags=tags) @main_page_module.route('/view_tag/<tag_id>') def view_tag(tag_id): tag = tag_get_one(tag_id) if (tag is None): flash('The tag does not exist !', 'error') return redirect(url_for("main_page_module.all_locations")) locations = location_get_all_with_tag(tag_id) return render_template("main_page_module/view_tag.html", tag=tag, locations=locations) @main_page_module.route('/remove_tag/', methods=['POST']) @login_required def remove_tag(): loc_tag_id = request.form["loc_tag_id"] loc_tag = loc_tag_get_one(loc_tag_id) json_response = {"a": "OK"} if loc_tag is not None: loc_tag_remove(loc_tag_id, loc_tag[2]) return jsonify(json_response) else: json_response = {"a": "-1"} return jsonify(json_response) @main_page_module.route('/add_tag/', methods=['POST']) @login_required def add_tag(): location = location_get_one(request.form["loc_id"]) tag = tag_get_one(request.form["tag_id"]) json_response = {"a": "OK"} if (location is not None) and (tag is not None): if loc_tag_get_one_by(location[0], tag[0]) is None: tag_add(location[0], tag[0]) return jsonify(json_response) else: json_response = {"a": "KO"} return jsonify(json_response) else: json_response = {"a": "-1"} return jsonify(json_response) @main_page_module.route('/create_tag/', methods=['POST']) @login_required def create_tag(): form = TagForm(request.form) location = location_get_one(form.id.data) # Verify the sign in form if (form.validate_on_submit()) and (location is not None): tag_create(form.name.data, form.id.data) flash('Tag successfully created for this location!', 'success') return redirect(url_for("main_page_module.edit_location", location_id=form.id.data)) for error in form.errors: print(error) flash('No access or the location does not exist!', 'error') return redirect(url_for("main_page_module.index")) @main_page_module.route('/add_img/', methods=['POST']) @login_required def add_img(): form = ImgForm(request.form) location = location_get_one(form.id.data) # Verify the sign in form if (form.validate_on_submit()) and (location is not None): img_create(form.name.data, form.link.data, form.id.data) flash('Location successfully Eddited!', 'success') return redirect(url_for("main_page_module.edit_location", location_id=form.id.data)) for error in form.errors: print(error) flash('No access or the location does not exist!', 'error') return redirect(url_for("main_page_module.index")) @main_page_module.route('/remove_img/', methods=['POST']) @login_required def remove_img(): img_id = request.form["img_id"] img = img_get_one(img_id) json_response = {"a": "OK"} if img is not None: img_remove(img_id) return jsonify(json_response) else: json_response = {"a": "-1"} return jsonify(json_response) @main_page_module.route('/add_parking/', methods=['POST']) @login_required def add_parking(): form = ParkingForm(request.form) location = location_get_one(form.id.data) # Verify the sign in form if (form.validate_on_submit()) and (location is not None): parking_create(form.name.data, form.price.data, form.coord.data.replace(" ", ""), form.id.data) flash('Location successfully Eddited!', 'success') return redirect(url_for("main_page_module.edit_location", location_id=form.id.data)) for error in form.errors: print(error) flash('No access or the location does not exist!', 'error') return redirect(url_for("main_page_module.index")) @main_page_module.route('/remove_parking/', methods=['POST']) @login_required def remove_parking(): parking_id = request.form["parking_id"] parking = parking_get_one(parking_id) json_response = {"a": "OK"} if parking is not None: parking_remove(parking_id) return jsonify(json_response) else: json_response = {"a": "-1"} return jsonify(json_response) @main_page_module.route('/new_icon', methods=['GET', 'POST']) @login_required def new_icon(): # If sign in form is submitted form = IconForm(request.form) # Verify the sign in form if form.validate_on_submit(): icon_id = icon_create(form.name.data, form.link.data) flash('Ikona ustvarjena!', 'success') return redirect(url_for("main_page_module.index")) for error in form.errors: print(error) return render_template("main_page_module/locations/new_icon.html", form=form) @main_page_module.route('/new_location', methods=['GET', 'POST']) @login_required def new_location(): # If sign in form is submitted form = LocationForm(request.form) # Verify the sign in form if form.validate_on_submit(): coordinates = form.coord.data location_id = location_create(form.name.data, form.desc_s.data, form.desc_l.data, form.rating.data, form.tts.data, coordinates.replace(" ", ""), form.mtld.data, form.contact.data, remove_https(form.webpage.data), form.timetable.data, form.fee.data, form.fee_price.data, form.child.data, form.season.data, form.icon.data) #create argus index locations = location_get_all_argus() new_index = WSearch() new_index.index_create_loc(locations) flash('Location successfully created!', 'success') return redirect(f"edit_location/{location_id}") """ for error in form.errors: print(error) """ return render_template("main_page_module/locations/new_location.html", form=form) @main_page_module.route('/edit_location/<location_id>', methods=['GET', 'POST']) @login_required def edit_location(location_id): location = location_get_one(location_id) form_parking = ParkingForm() form_img = ImgForm() form_tag = TagForm() if location is None: flash('No entry found', 'error') return redirect(url_for("main_page_module.index")) form = LocationForm() form.process(id = location_id, name = location[1], desc_s = location[2], desc_l = location[3], rating = location[4], tts = location[5], coord = location[6].replace(" ", ""), mtld = location[7], contact = location[8], webpage = location[14], timetable = location[9], fee = location[10], fee_price = location[15], child = location[11], season = location[12], icon = location[13]) parkings = parking_get_all_of_location(location_id) tags = tag_get_all_of_location(location_id) all_tags = tag_get_all() all_imgs = img_get_all_of_location(location_id) return render_template("main_page_module/locations/edit_location.html", form=form, form_parking=form_parking, form_tag=form_tag, form_img=form_img, parkings=parkings, tags=tags, all_tags=all_tags, icon_get_one=icon_get_one, all_imgs=all_imgs) @main_page_module.route('/view_location/<location_id>', methods=['GET', 'POST']) def view_location(location_id): location = location_get_one(location_id) parkings = parking_get_all_of_location(location_id) tags = tag_get_all_of_location(location_id) all_imgs = img_get_all_of_location(location_id) if location is None: flash('No Location found', 'error') return redirect(url_for("main_page_module.index")) return render_template("main_page_module/locations/view_location.html", location=location, parkings=parkings, tags=tags, icon_get_one=icon_get_one, all_imgs=all_imgs) @main_page_module.route('/change_location/', methods=['POST']) @login_required def change_location(): form = LocationForm(request.form) location_id = form.id.data location = location_get_one(location_id) if form.validate_on_submit(): if location is None: flash('No location found', 'error') return redirect(url_for("main_page_module.index")) location_change(location_id, form.name.data, form.desc_s.data, form.desc_l.data, form.rating.data, form.tts.data, form.coord.data, form.mtld.data, form.contact.data, remove_https(form.webpage.data), form.timetable.data, form.fee.data, form.fee_price.data, form.child.data, form.season.data, form.icon.data) flash('Location successfully Eddited!', 'success') return redirect(url_for("main_page_module.edit_location", location_id=location_id)) flash('Invalid Data', 'error') for error in form.errors: print(error) return redirect(url_for("main_page_module.index")) @main_page_module.route('/get_zipped_entries/') @login_required def get_zipped_entries(): now = datetime.datetime.now() base_path = pathlib.Path('app//main_page_module//data//') data = io.BytesIO() with zipfile.ZipFile(data, mode='w') as z: for f_name in base_path.iterdir(): z.write(f_name, os.path.basename(f_name)) data.seek(0) return send_file( data, mimetype='application/zip', as_attachment=True, attachment_filename=f'all_entries_{now.strftime("%Y-%m-%d_%H-%M")}.zip', cache_timeout=0 ) @main_page_module.route('/admin/all_users/') @login_required def all_users(): users = user_sql_get_all() return render_template("main_page_module/admin/all_users.html", users=users) @main_page_module.route('/admin/view_user/<user_id>') @login_required def view_user(user_id): user = user_sql_get_one(user_id) if not user: flash('User does not exist.', 'error') return redirect(url_for("main_page_module.all_users")) form = EditUserForm() form.process(id = user[0], name = user[1], email = user[3]) return render_template("main_page_module/admin/view_user.html", form=form, user=user) @main_page_module.route('/admin/modify_user/', methods=['POST']) @login_required def modify_user(): form = EditUserForm(request.form) if form.validate_on_submit(): user = user_sql_get_one(form.id.data) if not user: flash('User does not exist.', 'error') return redirect(url_for("main_page_module.all_users")) user_sql_update_one(form.id.data, form.name.data, form.email.data, form.password.data) flash('User successfully Eddited!', 'success') return redirect(url_for("main_page_module.view_user", user_id=form.id.data, form=form)) flash('Invalid data.', 'error') return redirect(url_for("main_page_module.all_users")) @main_page_module.route('/admin/delete/', methods=['POST']) @login_required def delete_user(): user = user_sql_get_one(request.form["id"]) if not user: flash('User does not exist.', 'error') return redirect(url_for("main_page_module.all_users")) else: user_sql_delete_one(user[0]) flash(f'User {user[1]} - {user[2]} successfully deleted.', 'success') return redirect(url_for("main_page_module.all_users")) # Set the route and accepted methods @main_page_module.route('/login/', methods=['GET', 'POST']) def login(): # If sign in form is submitted form = LoginForm(request.form) # Verify the sign in form if form.validate_on_submit(): user_id = user_sql_login_check(form.username_or_email.data, form.password.data) if user_id is not False: session['user_id'] = user_id[0] #set permanent login, if selected if form.remember.data == True: session.permanent = True flash('Welcome %s' % user_id[1], 'success') return redirect(url_for('main_page_module.index')) flash('Wrong email or password', 'error') try: if(session['user_id']): return redirect(url_for("main_page_module.index")) except: return render_template("main_page_module/auth/login.html", form=form) @main_page_module.route('/logout/') @login_required def logout(): session.pop("user_id", None) session.permanent = False flash('You have been logged out. Have a nice day!', 'success') return redirect(url_for("main_page_module.login")) # Set the route and accepted methods @main_page_module.route('/register/', methods=['GET', 'POST']) def register(): #insert check, if the user is already logged in ''' form = RegisterForm(request.form) if form.validate_on_submit(): user_sql_create(form.username.data, form.email.data, form.password.data) flash('Congratulations, you are now a registered user!', 'success') return redirect(url_for('main_page_module.login')) return render_template('main_page_module/auth/register.html', title='Register', form=form) ''' flash('Registracija uporabnikov še ni možna!', 'error') return redirect(url_for('main_page_module.index'))
{"/run.py": ["/app/__init__.py"], "/app/main_page_module/controllers.py": ["/app/main_page_module/forms.py", "/app/main_page_module/other.py", "/app/main_page_module/models.py", "/app/main_page_module/argus.py"], "/app/__init__.py": ["/app/main_page_module/controllers.py"], "/app/main_page_module/models.py": ["/app/__init__.py"], "/app/main_page_module/forms.py": ["/app/main_page_module/models.py"]}
70,014
Charckle/svetovifprequel
refs/heads/master
/config.py
import sys from os import environ DB_HOST = environ.get('DB_HOST', "127.0.0.1") DB_NAME = environ.get('DB_NAME', "svetovidprequel") DB_USERNAME = environ.get('DB_USERNAME', "root") DB_PASSWORD = environ.get('DB_PASSWORD', "") class Config(object): DEBUG = False TESTING = False SECRET_KEY = environ.get('SECRET_KEY', "B\xb2?.\xdf\x9f\xa7m\xf8\x8a%,\xf7\xc4\xfa\x91") IMAGE_UPLOADS = "/home/username/app/app/static/images/uploads" SESSION_COOKIE_SECURE = True # Application threads. A common general assumption is # using 2 per available processor cores - to handle # incoming requests using one and performing background # operations using the other. THREADS_PER_PAGE = 2 # Enable protection agains *Cross-site Request Forgery (CSRF)* CSRF_ENABLED = True class ProductionConfig(Config): DB_HOST = DB_HOST DB_NAME = DB_NAME DB_USERNAME = DB_USERNAME DB_PASSWORD = DB_PASSWORD class DevelopmentConfig(Config): DEBUG = True DB_HOST = DB_HOST DB_NAME = DB_NAME DB_USERNAME = DB_USERNAME DB_PASSWORD = DB_PASSWORD SESSION_COOKIE_SECURE = False class TestingConfig(Config): TESTING = True DB_HOST = DB_HOST DB_NAME = DB_NAME DB_USERNAME = DB_USERNAME DB_PASSWORD = DB_PASSWORD SESSION_COOKIE_SECURE = False
{"/run.py": ["/app/__init__.py"], "/app/main_page_module/controllers.py": ["/app/main_page_module/forms.py", "/app/main_page_module/other.py", "/app/main_page_module/models.py", "/app/main_page_module/argus.py"], "/app/__init__.py": ["/app/main_page_module/controllers.py"], "/app/main_page_module/models.py": ["/app/__init__.py"], "/app/main_page_module/forms.py": ["/app/main_page_module/models.py"]}
70,015
Charckle/svetovifprequel
refs/heads/master
/app/__init__.py
# Import flask and template operators from flask import Flask, render_template import time from os import environ # Import SQLite3 import MySQLdb # Define the WSGI application object app = Flask(__name__) # Configurations if environ.get('ENVCONFIG', "DEV") != 'PROD': app.config.from_object("config.DevelopmentConfig") else: app.config.from_object("config.ProductionConfig") #connection = sqlite3.connect("sqlite:///razor_notes.sqlite3") sql_host = app.config['DB_HOST'] sql_user = app.config['DB_USERNAME'] sql_passwrd = app.config['DB_PASSWORD'] sql_db = app.config['DB_NAME'] class DB: conn = None def connect(self): self.conn = MySQLdb.connect(use_unicode = True, charset = "utf8", host = sql_host, user = sql_user, passwd = sql_passwrd, db = sql_db) def query(self, sql, variables): try: cursor = self.conn.cursor() cursor.execute(sql, variables) except (AttributeError, MySQLdb.OperationalError): self.connect() cursor = self.conn.cursor() cursor.execute(sql, variables) return cursor db = DB() # Sample HTTP error handling @app.errorhandler(404) def not_found(error): return render_template('404.html'), 404 @app.route('/robots.txt') def static_file(): return app.send_static_file("robots.txt") # Import a module / component using its blueprint handler variable (mod_auth) from app.main_page_module.controllers import main_page_module as main_module # Register blueprint(s) app.register_blueprint(main_module) # app.register_blueprint(xyz_module) # ..
{"/run.py": ["/app/__init__.py"], "/app/main_page_module/controllers.py": ["/app/main_page_module/forms.py", "/app/main_page_module/other.py", "/app/main_page_module/models.py", "/app/main_page_module/argus.py"], "/app/__init__.py": ["/app/main_page_module/controllers.py"], "/app/main_page_module/models.py": ["/app/__init__.py"], "/app/main_page_module/forms.py": ["/app/main_page_module/models.py"]}
70,016
Charckle/svetovifprequel
refs/heads/master
/app/main_page_module/models.py
from datetime import datetime from app import db # Import password / encryption helper tools #from werkzeug import check_password_hash, generate_password_hash from werkzeug.security import generate_password_hash, check_password_hash def icon_create(name, link): sql_command = f"""INSERT INTO icons (name, link) VALUES (%s, %s);""" cursor = db.query(sql_command, (name, link)) db.conn.commit() icon_id = cursor.lastrowid return icon_id def icon_change(icon_id, name, link): sql_command = f"""UPDATE icons SET name = %s, link = %s WHERE id = %s;""" cursor = db.query(sql_command, (name, link, icon_id)) db.conn.commit() def icon_get_one(icon_id): sql_command = f"SELECT * FROM icons WHERE id = %s;" cursor = db.query(sql_command, (icon_id,)) result = cursor.fetchone() return result def icon_get_all(): sql_command = f"SELECT * FROM icons ORDER BY name ASC;" cursor = db.query(sql_command, ()) result = cursor.fetchall() return result def mtag_create(name, myth_id): try: sql_command = f"""INSERT INTO mtags (name) VALUES (%s);""" cursor = db.query(sql_command, (name,)) mtag_id = cursor.lastrowid #add tag to location sql_command = f"""INSERT INTO myth_mtag (id_mtag, id_myth) VALUES (%s, %s);""" cursor = db.query(sql_command, (id_mtag, id_myth)) db.conn.commit() except: db.conn.rollback() def mtag_add(myth_id, mtag_id): sql_command = f"""INSERT INTO myth_mtag (id_mtag, id_myth) VALUES (%s, %s);""" cursor = db.query(sql_command, (myth_id, mtag_id)) db.conn.commit() def myth_mtag_get_one(myth_mtag_id): sql_command = f"SELECT * FROM myth_mtag WHERE id = %s;" cursor = db.query(sql_command, (myth_mtag_id,)) result = cursor.fetchone() return result def myth_mtag_get_one_by(myth_id, mtag_id): sql_command = f"SELECT * FROM myth_mtag WHERE id_myth = %s AND id_mtag = %s ;" cursor = db.query(sql_command, (myth_id, mtag_id)) result = cursor.fetchone() return result def mtag_get_one(mtag_id): sql_command = f"SELECT * FROM mtags WHERE id = %s;" cursor = db.query(sql_command, (mtag_id,)) result = cursor.fetchone() return result def myth_mtag_remove(myth_mtag_id, id_mtag): sql_command = f"DELETE FROM myth_mtag WHERE id = %s ;" cursor = db.query(sql_command, (myth_mtag_id,)) db.conn.commit() try: #delete the tag connection sql_command = f"DELETE FROM myth_mtag WHERE id = %s;" cursor = db.query(sql_command, (myth_mtag_id,)) db.conn.commit() #check if the tag is connected to anything anymore sql_command = f"SELECT * FROM myth_mtag WHERE id_mtag = %s;" cursor = db.query(sql_command, (id_mtag,)) results = cursor.fetchall() #if not, delete it if (len(results) is 0): sql_command = f"DELETE FROM mtags WHERE id = %s;" cursor = db.query(sql_command, (id_mtag,)) db.conn.commit() except: db.conn.rollback() def mtag_get_all(): sql_command = f"SELECT * FROM mtags;" cursor = db.query(sql_command, ()) result = cursor.fetchall() return result def mtag_get_numbers(): sql_command = f"SELECT COUNT(*) FROM mtags;" cursor = db.query(sql_command, ()) result = cursor.fetchone() return result def mtag_get_all_of_myth(myth_id): sql_command = f"SELECT * FROM myth_mtag LEFT JOIN mtags ON myth_mtag.id_mtag = mtags.id WHERE myth_mtag.id_myth = %s;" cursor = db.query(sql_command, (myth_id,)) result = cursor.fetchall() return result def myth_create(name, desc_s, desc_l, coord, info): sql_command = f"""INSERT INTO myths (name, desc_s, desc_l, coord, info) VALUES (%s, %s, %s, %s, %s);""" cursor = db.query(sql_command, (name, desc_s, desc_l, coord, info)) db.conn.commit() myth_id = cursor.lastrowid return myth_id def myth_get_one(myth_id): sql_command = f"SELECT * FROM myths WHERE id = %s;" cursor = db.query(sql_command, (myth_id,)) result = cursor.fetchone() return result def myth_get_all(): sql_command = f"SELECT id, name, LEFT(desc_s , 100) FROM myths ;" cursor = db.query(sql_command, ()) result = cursor.fetchall() return result def myth_get_numbers(): sql_command = f"SELECT COUNT(*) FROM myths;" cursor = db.query(sql_command, ()) result = cursor.fetchone() return result def myth_get_all_with_mtag(mtag_id): sql_command = f"SELECT myths.id, myths.name, myths.desc_s FROM myth_mtag LEFT JOIN myths ON myth_mtag.id_myth = myths.id WHERE myth_mtag.id_mtag = %s;" cursor = db.query(sql_command, (mtag_id,)) result = cursor.fetchall() return result def myth_get_all_with_mtag_for_argus(mtag_id): sql_command = f"SELECT myths.id FROM myth_mtag LEFT JOIN myths ON myth_mtag.id_myth = myths.id WHERE myth_mtag.id_mtag = %s;" cursor = db.query(sql_command, (mtag_id,)) result = cursor.fetchall() return result def myth_change(myth_id, name, desc_s, desc_l, coord, info): sql_command = f"""UPDATE myths SET name = %s, desc_s = %s, desc_l = %s, coord = %s, info = %s WHERE id = %s;""" cursor = db.query(sql_command, (name, desc_s, desc_l, coord, info, myth_id)) db.conn.commit() def myth_delete_one(myth_id): sql_command = f"DELETE FROM myths WHERE id = %s;" cursor = db.query(sql_command, (myth_id,)) db.conn.commit() def loc_tag_remove(loc_tag_id, id_tag): sql_command = f"DELETE FROM loc_tag WHERE id = %s ;" cursor = db.query(sql_command, (loc_tag_id,)) db.conn.commit() try: #delete the tag connection sql_command = f"DELETE FROM loc_tag WHERE id = %s;" cursor = db.query(sql_command, (loc_tag_id,)) db.conn.commit() #check if the tag is connected to anything anymore sql_command = f"SELECT * FROM loc_tag WHERE id_tag = %s;" cursor = db.query(sql_command, (id_tag,)) results = cursor.fetchall() #if not, delete it if (len(results) is 0): sql_command = f"DELETE FROM tags WHERE id = %s;" cursor = db.query(sql_command, (id_tag,)) db.conn.commit() except: db.conn.rollback() def tag_create(name, location_id): try: sql_command = f"""INSERT INTO tags (name) VALUES (%s);""" cursor = db.query(sql_command, (name,)) tag_id = cursor.lastrowid #add tag to location sql_command = f"""INSERT INTO loc_tag (id_tag, id_loc) VALUES (%s, %s);""" cursor = db.query(sql_command, (tag_id, location_id)) db.conn.commit() except: db.conn.rollback() def tag_add(location_id, tag_id): sql_command = f"""INSERT INTO loc_tag (id_loc, id_tag) VALUES (%s, %s);""" cursor = db.query(sql_command, (location_id, tag_id)) db.conn.commit() def loc_tag_get_one(loc_tag_id): sql_command = f"SELECT * FROM loc_tag WHERE id = %s;" cursor = db.query(sql_command, (loc_tag_id,)) result = cursor.fetchone() return result def loc_tag_get_one_by(location_id, tag_id): sql_command = f"SELECT * FROM loc_tag WHERE id_loc = %s AND id_tag = %s ;" cursor = db.query(sql_command, (location_id, tag_id)) result = cursor.fetchone() return result def tag_get_one(tag_id): sql_command = f"SELECT * FROM tags WHERE id = %s;" cursor = db.query(sql_command, (tag_id,)) result = cursor.fetchone() return result def tag_get_all(): sql_command = f"SELECT * FROM tags ORDER BY name;" cursor = db.query(sql_command, ()) result = cursor.fetchall() return result def tag_get_numbers(): sql_command = f"SELECT COUNT(*) FROM tags;" cursor = db.query(sql_command, ()) result = cursor.fetchone() return result def tag_get_all_of_location(location_id): sql_command = f"SELECT * FROM loc_tag LEFT JOIN tags ON loc_tag.id_tag = tags.id WHERE loc_tag.id_loc = %s;" cursor = db.query(sql_command, (location_id,)) result = cursor.fetchall() return result def tag_change(tag_id, name): sql_command = f"""UPDATE tags SET name = %s WHERE id = %s;""" cursor = db.query(sql_command, (name, tag_id)) db.conn.commit() def img_create(name, link, location_id): sql_command = f"""INSERT INTO imgs (name, link, id_location) VALUES (%s, %s, %s);""" cursor = db.query(sql_command, (name, link, location_id)) db.conn.commit() img_id = cursor.lastrowid return img_id def img_get_one(img_id): sql_command = f"SELECT * FROM imgs WHERE id = %s;" cursor = db.query(sql_command, (img_id,)) result = cursor.fetchone() #print(result) return result def img_get_all_of_location(location_id): sql_command = f"SELECT * FROM imgs WHERE id_location = %s;" cursor = db.query(sql_command, (location_id,)) result = cursor.fetchall() return result def img_remove(img_id): sql_command = f"DELETE FROM imgs WHERE id = %s ;" cursor = db.query(sql_command, (img_id,)) db.conn.commit() def parking_create(name, cost, coord, location_id): sql_command = f"""INSERT INTO parkings (name, cost, coord, id_location) VALUES (%s, %s, %s, %s);""" cursor = db.query(sql_command, (name, cost, coord, location_id)) db.conn.commit() def parking_get_one(parking_id): sql_command = f"SELECT * FROM parkings WHERE id = %s;" cursor = db.query(sql_command, (parking_id,)) result = cursor.fetchone() return result def parking_get_all_of_location(location_id): sql_command = f"SELECT * FROM parkings WHERE id_location = %s;" cursor = db.query(sql_command, (location_id,)) result = cursor.fetchall() return result def parking_change(parking_id, cost, coord): sql_command = f"""UPDATE parkings SET name = %s, cost = %s, coord = %s WHERE id = %s;""" cursor = db.query(sql_command, (name, cost, coord, parking_id)) db.conn.commit() def parking_remove(parking_id): sql_command = f"DELETE FROM parkings WHERE id = %s ;" cursor = db.query(sql_command, (parking_id,)) db.conn.commit() def icon_create(name, link): sql_command = f"""INSERT INTO icons (name, link) VALUES (%s, %s);""" cursor = db.query(sql_command, (name, link)) db.conn.commit() icon_id = cursor.lastrowid return icon_id def location_create(name, desc_s, desc_l, rating, tts, coord, mtld, contact, timetable, fee, fee_price, child, season, icon): sql_command = f"""INSERT INTO locations (name, desc_s, desc_l, rating, tts, coord, mtld, contact, webpage, timetable, fee, fee_price, child, season, icon) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);""" cursor = db.query(sql_command, (name, desc_s, desc_l, rating, tts, coord, mtld, contact, webpage, timetable, fee, fee_price, child, season, icon)) db.conn.commit() location_id = cursor.lastrowid return location_id def location_get_all(): sql_command = f"SELECT locations.id, locations.name, LEFT(locations.desc_s , 100), icons.link, locations.coord, imgs.link FROM locations LEFT JOIN icons ON icons.id = locations.icon LEFT JOIN imgs ON imgs.id_location = locations.id GROUP BY locations.id ORDER BY locations.id DESC;" cursor = db.query(sql_command, ()) result = cursor.fetchall() #print(result) return result def location_get_all_where(command): sql_command = f"""SELECT locations.id, locations.name, LEFT(locations.desc_s , 100), icons.link, locations.coord, imgs.link FROM locations LEFT JOIN loc_tag ON loc_tag.id_loc = locations.id LEFT JOIN icons ON icons.id = locations.icon LEFT JOIN imgs ON imgs.id_location = locations.id WHERE locations.id > 0 %s GROUP BY locations.id ;""" cursor = db.query(sql_command, (command,)) result = cursor.fetchall() return result def location_get_all_where_rating(rating): sql_command = f"SELECT id FROM locations WHERE rating = %s;" cursor = db.query(sql_command, (rating,)) result = cursor.fetchall() return result def location_get_all_argus(): sql_command = f"SELECT id, name, desc_l FROM locations ;" cursor = db.query(sql_command, ()) result = cursor.fetchall() return result def myths_get_all_argus(): sql_command = f"SELECT id, name, desc_l FROM myths ;" cursor = db.query(sql_command, ()) result = cursor.fetchall() return result def location_get_all_with_ids(ids): ids = ','.join([str(i) for i in ids]) sql_command = f"SELECT locations.id, locations.name, LEFT(locations.desc_s , 100), icons.link, locations.coord, imgs.link FROM locations LEFT JOIN icons ON icons.id = locations.icon LEFT JOIN imgs ON imgs.id_location = locations.id WHERE locations.id IN (%s) GROUP BY locations.id;" cursor = db.query(sql_command, (ids,)) result = cursor.fetchall() return result def location_get_all_with_tag(tag_id): sql_command = f"SELECT locations.id, locations.name, locations.desc_s, icons.link FROM loc_tag LEFT JOIN locations ON loc_tag.id_loc = locations.id LEFT JOIN icons ON icons.id = locations.icon WHERE loc_tag.id_tag = %s;" cursor = db.query(sql_command, (tag_id,)) result = cursor.fetchall() return result def location_get_all_id_with_tag(tag_id): sql_command = f"SELECT locations.id FROM loc_tag LEFT JOIN locations ON loc_tag.id_loc = locations.id LEFT JOIN icons ON icons.id = locations.icon WHERE loc_tag.id_tag = %s;" cursor = db.query(sql_command, (tag_id,)) result = cursor.fetchall() return result def location_get_all_with_tag_for_argus(tag_id): sql_command = f"SELECT locations.id FROM loc_tag LEFT JOIN locations ON loc_tag.id_loc = locations.id WHERE loc_tag.id_tag = %s;" cursor = db.query(sql_command, (tag_id,)) result = cursor.fetchall() return result def location_get_one(location_id): sql_command = f"SELECT * FROM locations LEFT JOIN icons ON icons.id = locations.icon WHERE locations.id = %s;" cursor = db.query(sql_command, (location_id,)) result = cursor.fetchone() return result def location_get_icon_link(location_id): sql_command = f"SELECT icons.link FROM locations LEFT JOIN icons ON icons.id = locations.icon WHERE locations.id = %s ;" cursor = db.query(sql_command, (location_id,)) result = cursor.fetchone() return result def location_get_numbers(): sql_command = f"SELECT COUNT(*) FROM locations;" cursor = db.query(sql_command, ()) result = cursor.fetchone() return result def location_change(location_id, name, desc_s, desc_l, rating, tts, coord, mtld, contact, webpage, timetable, fee, fee_price, child, season, icon): sql_command = f"""UPDATE locations SET name = %s, desc_s = %s, desc_l = %s, rating = %s, tts = %s, coord = %s, mtld = %s, contact = %s, webpage = %s, timetable = %s, fee = %s, fee_price = %s, child = %s, season = %s, icon = %s WHERE id = %s;""" cursor = db.query(sql_command, (name, desc_s, desc_l, rating, tts, coord, mtld, contact, webpage, timetable, fee, fee_price, child, season, icon, location_id)) db.conn.commit() def location_delete_one(location_id): try: sql_command = f"DELETE FROM imgs WHERE id_location = %s;" cursor = db.query(sql_command, (location_id,)) sql_command = f"DELETE FROM locations WHERE id = %s;" cursor = db.query(sql_command, (location_id,)) db.conn.commit() except: db.conn.rollback() def user_sql_create(username, email, password): password_hash = generate_password_hash(password) sql_command = f"""INSERT INTO users (name, username, email, password, status) VALUES (%s, %s, %s, %s, True);""" cursor = db.query(sql_command, (username, username, email, password_hash)) db.conn.commit() def user_sql_check_username(username): sql_command = f"SELECT id, username, password FROM users WHERE (%s = username);" cursor = db.query(sql_command, (username,)) results = cursor.fetchone() #is a user is found, returns its ID if results is not None: return results return False def user_get_id_from_username(username): sql_command = f"SELECT id FROM users WHERE (%s = username);" cursor = db.query(sql_command, (username,)) results = cursor.fetchone() return results def user_sql_check_email(email): sql_command = f"SELECT id, email, password FROM users WHERE (%s = email);" cursor = db.query(sql_command, (email,)) results = cursor.fetchone() #is a user is found, returns its ID if results is not None: return results return False def user_sql_login_check(username_or_email, password): sql_command = f"SELECT id, username, email, password FROM users WHERE (%s = username) OR (%s = email);" cursor = db.query(sql_command, (username_or_email, username_or_email)) results = cursor.fetchone() #is a user is found, returns its ID if results is not None: if check_password_hash(results[3], password): return results return False def user_sql_get_all(): sql_command = f"SELECT id, name, username FROM users;" cursor = db.query(sql_command, ()) results = cursor.fetchall() return results def user_sql_get_one(user_id): sql_command = f"SELECT * FROM users WHERE id = %s;" cursor = db.query(sql_command, (user_id,)) result = cursor.fetchone() return result def user_sql_delete_one(user_id): sql_command = f"DELETE FROM users WHERE id = %s;" cursor = db.query(sql_command, (user_id,)) db.conn.commit() def user_sql_update_one(user_id, name, email, password): password_for_sql = "" if password != "": password_hash = generate_password_hash(password) password_for_sql = f", password = '{password_hash}'" sql_command = f"UPDATE users SET name = %s, email = %s%s WHERE id = %s" cursor = db.query(sql_command, (name, email, password_for_sql, user_id)) db.conn.commit()
{"/run.py": ["/app/__init__.py"], "/app/main_page_module/controllers.py": ["/app/main_page_module/forms.py", "/app/main_page_module/other.py", "/app/main_page_module/models.py", "/app/main_page_module/argus.py"], "/app/__init__.py": ["/app/main_page_module/controllers.py"], "/app/main_page_module/models.py": ["/app/__init__.py"], "/app/main_page_module/forms.py": ["/app/main_page_module/models.py"]}
70,017
Charckle/svetovifprequel
refs/heads/master
/app/main_page_module/argus.py
import os.path from whoosh.index import create_in from whoosh.fields import Schema, TEXT, NUMERIC from whoosh.index import open_dir from whoosh.query import * from whoosh.qparser import QueryParser class WSearch(): #def __init__(self, storage_location = "app//main_page_module//data//"): #self.storage_location = storage_location def index_create_loc(self, locations): #print(notes) schema = Schema(location_id=NUMERIC(stored=True), location_name=TEXT(stored=True), content=TEXT(stored=True)) if not os.path.exists(".index_locations"): os.mkdir(".index_locations") ix = create_in(".index_locations", schema) writer = ix.writer() for f in locations: #print(f[2]) writer.add_document(location_id=u"{}".format(f[0]),location_name=u"{}".format(f[1]), content=u"{}".format(f[2])) writer.commit() def index_create_myth(self, myths): #print(notes) schema = Schema(myth_id=NUMERIC(stored=True), myth_name=TEXT(stored=True), content=TEXT(stored=True)) if not os.path.exists(".index_myths"): os.mkdir(".index_myths") ix = create_in(".index_myths", schema) writer = ix.writer() for f in myths: #print(f[2]) writer.add_document(myth_id=u"{}".format(f[0]),myth_name=u"{}".format(f[1]), content=u"{}".format(f[2])) writer.commit() def index_search_location(self, querystring): #print(querystring) ix = open_dir(".index_locations") parser = QueryParser("content", ix.schema) myquery = parser.parse(querystring) locations = [] with ix.searcher() as searcher: results = searcher.search(myquery) print(f"Found {len(results)} results.") for found in results: locations.append([found["location_id"], found["location_name"], found.highlights("content")]) #print(found.highlights("content")) return locations def index_search_myth(self, querystring): #print(querystring) ix = open_dir(".index_myths") parser = QueryParser("content", ix.schema) myquery = parser.parse(querystring) index_myths = [] with ix.searcher() as searcher: results = searcher.search(myquery) print(f"Found {len(results)} results.") for found in results: index_myths.append([found["myth_id"], found["myth_name"], found.highlights("content")]) #print(found.highlights("content")) return index_myths
{"/run.py": ["/app/__init__.py"], "/app/main_page_module/controllers.py": ["/app/main_page_module/forms.py", "/app/main_page_module/other.py", "/app/main_page_module/models.py", "/app/main_page_module/argus.py"], "/app/__init__.py": ["/app/main_page_module/controllers.py"], "/app/main_page_module/models.py": ["/app/__init__.py"], "/app/main_page_module/forms.py": ["/app/main_page_module/models.py"]}
70,018
Charckle/svetovifprequel
refs/heads/master
/app/main_page_module/forms.py
# Import Form and RecaptchaField (optional) from flask_wtf import FlaskForm # , RecaptchaField # Import Form elements such as TextField and BooleanField (optional) from wtforms import BooleanField, IntegerField, StringField, TextAreaField, PasswordField, HiddenField, SubmitField, SelectField, DecimalField, validators # BooleanField # Import Form validators from wtforms.validators import Email, EqualTo, ValidationError from app.main_page_module.models import user_sql_check_username, user_sql_check_email, icon_get_all #email verification import re import os.path # Define the login form (WTForms) class IconForm(FlaskForm): id = HiddenField('id', [validators.InputRequired(message='Dont fiddle around with the code!')]) name = StringField('Ime Ikone', [validators.InputRequired(message='Potrebno je vnesti ime Ikone'), validators.Length(max=50)]) link = StringField('Ime datoteke', [validators.InputRequired(message='Potrebno je vnesti ime datoteke ikone'), validators.Length(max=100)]) submit = SubmitField('Dodaj Ikono') # Define the login form (WTForms) class ImgForm(FlaskForm): id = HiddenField('id', [validators.InputRequired(message='Dont fiddle around with the code!')]) name = StringField('Ime Slike', [validators.InputRequired(message='Potrebno je vnesti ime Slike'), validators.Length(max=50)]) link = StringField('Povezava do slike', [validators.InputRequired(message='Potrebno je vnesti povezavo do Slike'), validators.Length(max=500)]) submit = SubmitField('Dodaj sliko') class MTagForm(FlaskForm): id = HiddenField('id', [validators.InputRequired(message='Dont fiddle around with the code!')]) name = StringField('Ime Oznake', [validators.InputRequired(message='Potrebno je vnesti ime Oznake'), validators.Length(max=50)]) submit = SubmitField('Ustvari Oznako') class MythForm(FlaskForm): id = HiddenField('id', [validators.InputRequired(message='Dont fiddle around with the code!')]) name = StringField('Ime Pripovedke', [validators.InputRequired(message='Ime Pripovedke'), validators.Length(max=50)]) desc_s = StringField('Kratek opis Pripovedke', [validators.InputRequired(message='Vpiši kratek opis'), validators.Length(max=100)]) desc_l = TextAreaField('Dolg opis Pripovedke', [validators.InputRequired(message='Vpiši dolg opis Pripovedke')]) coord = StringField('Koordinate izvora Pripovedke', [validators.InputRequired(message='Vnesi koordinate izvora Pripovedke'), validators.Length(max=50)]) info = TextAreaField('Viri', [validators.InputRequired(message='Viri Pripovedke')]) submit = SubmitField('Oddaj') class TagForm(FlaskForm): id = HiddenField('id', [validators.InputRequired(message='Dont fiddle around with the code!')]) name = StringField('Ime Oznake', [validators.InputRequired(message='Potrebno je vnesti ime Oznake'), validators.Length(max=50)]) submit = SubmitField('Ustvari Oznako') class ParkingForm(FlaskForm): id = HiddenField('id', [validators.InputRequired(message='Dont fiddle around with the code!')]) name = StringField('Ime Parkinga', [validators.InputRequired(message='Potrebno je vnesti ime Parkinga'), validators.Length(max=50)]) prices = [(0, 'Zastonj'), (1, 'Poceni'), (2, 'Drago')] price = SelectField('Cena Parkiranja', [validators.InputRequired(message='Izberi Ceno')], choices=prices, coerce=int) coord = StringField('Koordinate Parkinga', [validators.InputRequired(message='Potrebno je vnesti koordinate Parkinga'), validators.Length(max=50)]) submit = SubmitField('Dodaj Parking') class LocationForm(FlaskForm): id = HiddenField('id', [validators.InputRequired(message=u'Dont fiddle around with the code!')]) name = StringField(u'Ime lokacije', [validators.InputRequired(message=u'Vnesi ime Lokacije.'), validators.Length(max=50)]) desc_s = StringField(u'Kratek opis', [validators.InputRequired(message=u'Vnesi kratek opis Lokacije.'), validators.Length(max=100)]) desc_l = TextAreaField(u'Dolg opis', [validators.InputRequired(message=u'Vnesi dolg opis Lokacije.'), validators.Length(max=2000)]) #ratings = [(0, 'If you have time, go see it once'), (1, 'Nothing special, but nice to see'), (2, 'Worth seeing if you can spare the time'), (3, 'Check it out, you wont regret it'), (4, 'Really good, top and see it'), (5, 'A must every time!')] ratings = [(0, u'Če imaš čas, obišči enkrat'), (1, u'Nič posebnega, vendar lepo za videt'), (2, u'Vredno ogleda, če imaš čas'), (3, u'Obišči, ne bo ti žal'), (4, u'Zelo vredno! Ustavi se in obišči!')] rating = SelectField(u'Ocena', [validators.InputRequired(message=u'Izberi oceno.')], choices=ratings, coerce=int) #Time To Spend tts = IntegerField(u'Čas, katerega Lokacija zahteva/porabiš na lokaciji (minute)', [validators.InputRequired(message=u'Vnesi čas za Lokacijo.')]) coord = StringField(u'Koordinate Lokacije', [validators.InputRequired(message=u'Vnesi koordinate Lokacije.'), validators.Length(max=50)]) #mtlds = [(0, 'PP0 - Easy, do not bother to mention'), (1, 'PP1 - Peacefull walk'), (2, 'PP2 - Can have some climbing protections'), (3, 'PP3 - Climbing protections, but not exposed, phisical strenght needed'), (4, 'PP4 - Vertical, exposed route'), (5, 'PP5 - Basicaly rock climbing with steel cables'), (6, 'PP6 - Like 5 but harder and more vertical')] mtlds = [(0, u'PP0 - Lahko, ni vredno omembe'), (1, u'PP1 - Lažji sprehod/lažja phodna pot'), (2, u'PP2 - Pot, na določenih mestih zavarovana'), (3, u'PP3 - Zavarovana plezalna pot, vendar ne izpostavljena. Potrebna je fizična moč'), (4, u'PP4 - Navpična, zavarovana in izpostavljena plezalna pot'), (5, u'PP5 - V praksi navadno plezanje, s feratami'), (6, u'PP6 - Kot 5, le da težje in bolj navpično')] #Max To Location Difficulty mtld = SelectField(u'Maksimalna težavnost do Lokacije', [validators.InputRequired(message=u'Izberi Težavnost.')], choices=mtlds, coerce=int) webpage = StringField(u'Spletna stran', [validators.Length(max=100)]) contact = StringField(u'Kontakt', [validators.Length(max=100)]) timetable = TextAreaField(u'Urnik') fees = [(0, u'Ne'), (1, u'Odvisno'), (2, 'Da')] fee = SelectField('Vstopnina', [validators.InputRequired(message=u'Izberi, ali ima Lokacija vstopnino')], choices=fees, coerce=int) fee_price = DecimalField('Cena vstopnine v € (odrasli)', [validators.Optional()], places=2, default=0) childs = [(0, u'Ne'), (1, 'Odvisno'), (2, u'Da')] child = SelectField(u'Ali je Lokacija primerna za otroke', [validators.InputRequired(message=u'Izberi, ali je Lokacija primerna za otroke.')], choices=childs, coerce=int) seasons = [(0, u'Ne'), (1, u'Da')] season = SelectField(u'Ali je Lokacija odvisna od letnega časa/vremenski pogojev', [validators.InputRequired(message=u'Izberi, ali je Lokacija odvisna od letnega časa/vremenskih pogojev.')], choices=seasons, coerce=int) icons = [] icon = SelectField(u'Izberi ikono', [validators.InputRequired(message=u'Izberi lokacijo.')], choices=icons, coerce=int) submit = SubmitField(u'Oddaj') def __init__(self, *args, **kwargs): super(LocationForm, self).__init__(*args, **kwargs) self.icon.choices = [(i[0], i[1]) for i in icon_get_all()] class LoginForm(FlaskForm): username_or_email = StringField('Username or Email', [validators.InputRequired(message='Forgot your email address?')]) password = PasswordField('Password', [validators.InputRequired(message='Must provide a password.')]) remember = BooleanField() submit = SubmitField('Login') class EditUserForm(FlaskForm): id = HiddenField('id', [validators.InputRequired(message='Dont fiddle around with the code!')]) name = StringField('Name', [validators.InputRequired(message='We need a name for the user.')]) email = StringField('Email', [validators.InputRequired(message='We need an email for your account.')]) password = PasswordField('Password') password_2 = PasswordField('Repeat password', [EqualTo('password', message='Passwords must match')]) submit = SubmitField('Submit changes') class RegisterForm(FlaskForm): username = StringField('Username', [validators.InputRequired(message='We need a username for your account.')]) email = StringField('Email', [validators.InputRequired(message='We need an email for your account.')]) password = PasswordField('Password') password_2 = PasswordField('Repeat password', [validators.InputRequired(), EqualTo('password', message='Passwords must match')]) submit = SubmitField('Register') #When you add any methods that match the pattern validate_<field_name>, WTForms takes those as custom validators and invokes them in addition to the stock validators def validate_username(self, username): if user_sql_check_username(username.data) is not False: raise ValidationError('Please use a different username.') def validate_email(self, email): regex = '^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$' #check if it is a real email if(re.search(regex,email.data)): #if it is, check if there is another user with the same email if user_sql_check_username(email.data) is not False: raise ValidationError('Please use a different email address.') else: raise ValidationError('Please use a valid email address.')
{"/run.py": ["/app/__init__.py"], "/app/main_page_module/controllers.py": ["/app/main_page_module/forms.py", "/app/main_page_module/other.py", "/app/main_page_module/models.py", "/app/main_page_module/argus.py"], "/app/__init__.py": ["/app/main_page_module/controllers.py"], "/app/main_page_module/models.py": ["/app/__init__.py"], "/app/main_page_module/forms.py": ["/app/main_page_module/models.py"]}
70,019
Charckle/svetovifprequel
refs/heads/master
/app/main_page_module/other.py
import re def remove_https(link): webpage = re.sub(r'^https?:\/\/', '', link) return webpage
{"/run.py": ["/app/__init__.py"], "/app/main_page_module/controllers.py": ["/app/main_page_module/forms.py", "/app/main_page_module/other.py", "/app/main_page_module/models.py", "/app/main_page_module/argus.py"], "/app/__init__.py": ["/app/main_page_module/controllers.py"], "/app/main_page_module/models.py": ["/app/__init__.py"], "/app/main_page_module/forms.py": ["/app/main_page_module/models.py"]}
70,034
Dsthdragon/kizito_bookstore
refs/heads/master
/migrations/versions/eb502f9a5410_added_paid_to_order_model.py
"""Added paid to order model Revision ID: eb502f9a5410 Revises: 82df20a186ef Create Date: 2020-04-19 17:05:05.312230 """ from alembic import op import sqlalchemy as sa import sqlalchemy_utils # revision identifiers, used by Alembic. revision = 'eb502f9a5410' down_revision = '82df20a186ef' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('order', sa.Column('paid', sa.Boolean(), nullable=True)) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('order', 'paid') # ### end Alembic commands ###
{"/app/models.py": ["/config.py"], "/app/schemas.py": ["/app/models.py"], "/app/api/routes.py": ["/app/schemas.py"]}
70,035
Dsthdragon/kizito_bookstore
refs/heads/master
/migrations/versions/95b2f50b1799_changed_column_role_to_title_in_role_.py
"""Changed column role to title in role table Revision ID: 95b2f50b1799 Revises: f18377a6e8b9 Create Date: 2019-10-31 00:48:18.832954 """ from alembic import op import sqlalchemy as sa import sqlalchemy_utils from sqlalchemy.dialects import mysql # revision identifiers, used by Alembic. revision = '95b2f50b1799' down_revision = 'f18377a6e8b9' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('role', sa.Column('title', sa.String(length=100), nullable=False)) op.drop_column('role', 'role') # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('role', sa.Column('role', mysql.VARCHAR(length=100), nullable=False)) op.drop_column('role', 'title') # ### end Alembic commands ###
{"/app/models.py": ["/config.py"], "/app/schemas.py": ["/app/models.py"], "/app/api/routes.py": ["/app/schemas.py"]}
70,036
Dsthdragon/kizito_bookstore
refs/heads/master
/migrations/versions/82df20a186ef_added_name_to_store_address_model.py
"""Added name to Store Address model Revision ID: 82df20a186ef Revises: dbdc74926faf Create Date: 2020-04-19 14:13:49.983123 """ from alembic import op import sqlalchemy as sa import sqlalchemy_utils # revision identifiers, used by Alembic. revision = '82df20a186ef' down_revision = 'dbdc74926faf' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('store_address', sa.Column('name', sa.String(length=255), nullable=False)) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('store_address', 'name') # ### end Alembic commands ###
{"/app/models.py": ["/config.py"], "/app/schemas.py": ["/app/models.py"], "/app/api/routes.py": ["/app/schemas.py"]}
70,037
Dsthdragon/kizito_bookstore
refs/heads/master
/migrations/versions/f18377a6e8b9_init_migration.py
"""Init Migration Revision ID: f18377a6e8b9 Revises: Create Date: 2019-10-31 00:31:13.092268 """ from alembic import op import sqlalchemy as sa import sqlalchemy_utils # revision identifiers, used by Alembic. revision = 'f18377a6e8b9' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('category', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=255), nullable=False), sa.Column('link', sa.String(length=255), nullable=False), sa.Column('parent_id', sa.Integer(), nullable=True), sa.Column('created', sa.DateTime(), nullable=True), sa.Column('updated', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['parent_id'], ['category.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_table('country', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=255), nullable=False), sa.Column('short', sa.String(length=10), nullable=True), sa.Column('created', sa.DateTime(), nullable=True), sa.Column('updated', sa.DateTime(), nullable=True), sa.PrimaryKeyConstraint('id') ) op.create_table('creator', sa.Column('id', sa.Integer(), nullable=False), sa.Column('title', sa.String(length=500), nullable=False), sa.Column('created', sa.DateTime(), nullable=True), sa.PrimaryKeyConstraint('id') ) op.create_table('filter', sa.Column('id', sa.Integer(), nullable=False), sa.Column('title', sa.String(length=500), nullable=False), sa.Column('created', sa.DateTime(), nullable=True), sa.PrimaryKeyConstraint('id') ) op.create_table('role', sa.Column('id', sa.Integer(), nullable=False), sa.Column('role', sa.String(length=100), nullable=False), sa.Column('description', sa.String(length=1000), nullable=False), sa.Column('created', sa.DateTime(), nullable=True), sa.PrimaryKeyConstraint('id') ) op.create_table('user', sa.Column('id', sa.Integer(), nullable=False), sa.Column('created', sa.DateTime(), nullable=True), sa.PrimaryKeyConstraint('id') ) op.create_table('admin', sa.Column('id', sa.Integer(), nullable=False), sa.Column('role_id', sa.Integer(), nullable=False), sa.Column('fullname', sqlalchemy_utils.types.encrypted.encrypted_type.EncryptedType(), nullable=False), sa.Column('email', sqlalchemy_utils.types.encrypted.encrypted_type.EncryptedType(), nullable=False), sa.Column('password_hash', sa.String(length=400), nullable=False), sa.Column('avatar', sqlalchemy_utils.types.encrypted.encrypted_type.EncryptedType(), nullable=True), sa.Column('created', sa.DateTime(), nullable=True), sa.Column('updated', sa.DateTime(), nullable=True), sa.Column('user_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['role_id'], ['role.id'], ), sa.ForeignKeyConstraint(['user_id'], ['user.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_table('category_filter', sa.Column('id', sa.Integer(), nullable=False), sa.Column('category_id', sa.Integer(), nullable=False), sa.Column('filter_id', sa.Integer(), nullable=False), sa.Column('created', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['category_id'], ['category.id'], ), sa.ForeignKeyConstraint(['filter_id'], ['filter.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_table('client', sa.Column('id', sa.Integer(), nullable=False), sa.Column('email', sqlalchemy_utils.types.encrypted.encrypted_type.EncryptedType(), nullable=False), sa.Column('phone', sqlalchemy_utils.types.encrypted.encrypted_type.EncryptedType(), nullable=True), sa.Column('first_name', sqlalchemy_utils.types.encrypted.encrypted_type.EncryptedType(), nullable=False), sa.Column('last_name', sqlalchemy_utils.types.encrypted.encrypted_type.EncryptedType(), nullable=True), sa.Column('password_hash', sa.String(length=255), nullable=False), sa.Column('avatar', sqlalchemy_utils.types.encrypted.encrypted_type.EncryptedType(), nullable=True), sa.Column('created', sa.DateTime(), nullable=True), sa.Column('updated', sa.DateTime(), nullable=True), sa.Column('user_id', sa.Integer(), nullable=True), sa.ForeignKeyConstraint(['user_id'], ['user.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_table('filter_value', sa.Column('id', sa.Integer(), nullable=False), sa.Column('filter_id', sa.Integer(), nullable=False), sa.Column('value', sa.String(length=1000), nullable=False), sa.Column('created', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['filter_id'], ['filter.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_table('product', sa.Column('id', sa.Integer(), nullable=False), sa.Column('name', sa.String(length=500), nullable=False), sa.Column('creator_id', sa.Integer(), nullable=False), sa.Column('category_id', sa.Integer(), nullable=False), sa.Column('summary', sa.String(length=1000), nullable=True), sa.Column('description', sa.Text(), nullable=True), sa.Column('price', sa.Float(), nullable=False), sa.Column('created', sa.DateTime(), nullable=True), sa.Column('updated', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['category_id'], ['category.id'], ), sa.ForeignKeyConstraint(['creator_id'], ['creator.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_table('address', sa.Column('id', sa.Integer(), nullable=False), sa.Column('client_id', sa.Integer(), nullable=False), sa.Column('country_id', sa.Integer(), nullable=False), sa.Column('state', sa.String(length=255), nullable=False), sa.Column('city', sa.String(length=255), nullable=False), sa.Column('address', sa.String(length=500), nullable=False), sa.Column('postal_code', sa.String(length=10), nullable=True), sa.Column('created', sa.DateTime(), nullable=True), sa.Column('updated', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['client_id'], ['client.id'], ), sa.ForeignKeyConstraint(['country_id'], ['country.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_table('cart', sa.Column('id', sa.Integer(), nullable=False), sa.Column('client_id', sa.Integer(), nullable=False), sa.Column('complete', sa.Boolean(), nullable=True), sa.Column('created', sa.DateTime(), nullable=True), sa.Column('updated', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['client_id'], ['client.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_table('category_product', sa.Column('id', sa.Integer(), nullable=False), sa.Column('category_id', sa.Integer(), nullable=False), sa.Column('product_id', sa.Integer(), nullable=False), sa.ForeignKeyConstraint(['category_id'], ['category.id'], ), sa.ForeignKeyConstraint(['product_id'], ['product.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_table('product_filter', sa.Column('id', sa.Integer(), nullable=False), sa.Column('product_id', sa.Integer(), nullable=False), sa.Column('value_id', sa.Integer(), nullable=False), sa.Column('filter_id', sa.Integer(), nullable=False), sa.ForeignKeyConstraint(['filter_id'], ['filter.id'], ), sa.ForeignKeyConstraint(['product_id'], ['product.id'], ), sa.ForeignKeyConstraint(['value_id'], ['filter_value.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_table('product_image', sa.Column('id', sa.Integer(), nullable=False), sa.Column('product_id', sa.Integer(), nullable=False), sa.Column('image', sa.String(length=500), nullable=False), sa.Column('thumb', sa.String(length=500), nullable=False), sa.Column('created', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['product_id'], ['product.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_table('product_review', sa.Column('id', sa.Integer(), nullable=False), sa.Column('client_id', sa.Integer(), nullable=False), sa.Column('product_id', sa.Integer(), nullable=False), sa.Column('score', sa.Integer(), nullable=False), sa.Column('review', sa.Text(), nullable=False), sa.Column('created', sa.DateTime(), nullable=True), sa.Column('updated', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['client_id'], ['client.id'], ), sa.ForeignKeyConstraint(['product_id'], ['product.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_table('cart_item', sa.Column('id', sa.Integer(), nullable=False), sa.Column('cart_id', sa.Integer(), nullable=False), sa.Column('product_id', sa.Integer(), nullable=False), sa.Column('price', sa.Float(), nullable=False), sa.Column('unit_price', sa.Float(), nullable=False), sa.Column('quantity', sa.Float(), nullable=False), sa.Column('created', sa.DateTime(), nullable=True), sa.Column('updated', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['cart_id'], ['cart.id'], ), sa.ForeignKeyConstraint(['product_id'], ['product.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_table('order', sa.Column('id', sa.Integer(), nullable=False), sa.Column('cart_id', sa.Integer(), nullable=False), sa.Column('client_id', sa.Integer(), nullable=False), sa.Column('address_id', sa.Integer(), nullable=True), sa.Column('price', sa.Float(), nullable=False), sa.Column('reference', sa.String(length=1000), nullable=True), sa.Column('payment_type', sa.String(length=30), nullable=True), sa.Column('status', sa.Integer(), nullable=True), sa.Column('created', sa.DateTime(), nullable=True), sa.Column('updated', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['address_id'], ['address.id'], ), sa.ForeignKeyConstraint(['cart_id'], ['cart.id'], ), sa.ForeignKeyConstraint(['client_id'], ['client.id'], ), sa.PrimaryKeyConstraint('id') ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('order') op.drop_table('cart_item') op.drop_table('product_review') op.drop_table('product_image') op.drop_table('product_filter') op.drop_table('category_product') op.drop_table('cart') op.drop_table('address') op.drop_table('product') op.drop_table('filter_value') op.drop_table('client') op.drop_table('category_filter') op.drop_table('admin') op.drop_table('user') op.drop_table('role') op.drop_table('filter') op.drop_table('creator') op.drop_table('country') op.drop_table('category') # ### end Alembic commands ###
{"/app/models.py": ["/config.py"], "/app/schemas.py": ["/app/models.py"], "/app/api/routes.py": ["/app/schemas.py"]}
70,038
Dsthdragon/kizito_bookstore
refs/heads/master
/migrations/versions/dbdc74926faf_added_store_address_to_order_model.py
"""Added Store Address to order model Revision ID: dbdc74926faf Revises: 573eb06f3c5c Create Date: 2020-04-18 15:32:25.481011 """ from alembic import op import sqlalchemy as sa import sqlalchemy_utils # revision identifiers, used by Alembic. revision = 'dbdc74926faf' down_revision = '573eb06f3c5c' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('order', sa.Column('store_address_id', sa.Integer(), nullable=True)) op.create_foreign_key(None, 'order', 'store_address', ['store_address_id'], ['id'], ondelete='CASCADE') # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_constraint(None, 'order', type_='foreignkey') op.drop_column('order', 'store_address_id') # ### end Alembic commands ###
{"/app/models.py": ["/config.py"], "/app/schemas.py": ["/app/models.py"], "/app/api/routes.py": ["/app/schemas.py"]}
70,039
Dsthdragon/kizito_bookstore
refs/heads/master
/migrations/versions/743a12adbc4a_deleted_thumb_column_from_product_image.py
"""deleted thumb column from product_image Revision ID: 743a12adbc4a Revises: 02e4548ac30e Create Date: 2019-11-07 15:28:36.305007 """ from alembic import op import sqlalchemy as sa import sqlalchemy_utils from sqlalchemy.dialects import mysql # revision identifiers, used by Alembic. revision = '743a12adbc4a' down_revision = '02e4548ac30e' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('product_image', 'thumb') # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('product_image', sa.Column('thumb', mysql.VARCHAR(length=500), nullable=False)) # ### end Alembic commands ###
{"/app/models.py": ["/config.py"], "/app/schemas.py": ["/app/models.py"], "/app/api/routes.py": ["/app/schemas.py"]}
70,040
Dsthdragon/kizito_bookstore
refs/heads/master
/app/models.py
from datetime import datetime from PIL import Image from io import BytesIO import base64 import os import jwt from werkzeug.security import generate_password_hash, check_password_hash from sqlalchemy import event from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy_utils import EncryptedType from sqlalchemy_utils.types.encrypted.encrypted_type import AesEngine from app import db from config import Config import enum product_filters = db.Table('product_filters', db.Column('value_id', db.Integer, db.ForeignKey('filter_value.id'), primary_key=True), db.Column('product_id', db.Integer, db.ForeignKey('product.id'), primary_key=True), ) category_filters = db.Table('category_filters', db.Column('filter_id', db.Integer, db.ForeignKey('filter.id'), primary_key=True), db.Column('category_id', db.Integer, db.ForeignKey('category.id'), primary_key=True), ) product_categories = db.Table('product_categories', db.Column('category_id', db.Integer, db.ForeignKey('category.id'), primary_key=True), db.Column('product_id', db.Integer, db.ForeignKey('product.id'), primary_key=True) ) class User(db.Model): id = db.Column(db.Integer, primary_key=True) created = db.Column(db.DateTime, default=datetime.utcnow()) client = db.relationship("Client", backref=db.backref("user", lazy=True), uselist=False) admin = db.relationship("Admin", backref=db.backref("user", lazy=True), uselist=False) def generate_token(self): return jwt.encode( { 'id': self.id }, Config.SECRET_KEY, algorithm='HS256' ).decode() @staticmethod def decode_token(token): try: payload = jwt.decode(token, Config.SECRET_KEY) return payload['id'] except jwt.ExpiredSignatureError: return 'Signature expired. Please log in again.' except jwt.InvalidTokenError: return 'Invalid token. Please log in again.' class Client(db.Model): id = db.Column(db.Integer, primary_key=True) email = db.Column(EncryptedType(db.String, Config.SECRET_KEY, AesEngine, 'pkcs5'), nullable=False) phone = db.Column(EncryptedType(db.String, Config.SECRET_KEY, AesEngine, 'pkcs5'), nullable=True) first_name = db.Column(EncryptedType(db.String, Config.SECRET_KEY, AesEngine, 'pkcs5'), nullable=False) last_name = db.Column(EncryptedType(db.String, Config.SECRET_KEY, AesEngine, 'pkcs5')) password_hash = db.Column(db.String(255), nullable=False) avatar = db.Column(EncryptedType(db.String, Config.SECRET_KEY, AesEngine, 'pkcs5')) created = db.Column(db.DateTime, default=datetime.utcnow) updated = db.Column(db.DateTime, onupdate=datetime.utcnow) user_id = db.Column(db.Integer, db.ForeignKey("user.id", ondelete='CASCADE')) def set_password(self, password): self.password_hash = generate_password_hash(password) def check_password(self, password): return check_password_hash(self.password_hash, password) @hybrid_property def avatar_url(self): return "/static/upload/images/avatars/client/" + str(self.avatar) @staticmethod def crop_image(img, path): crop_height, crop_width = Config.AVATAR_CROP_SIZE width, height = img.size height_ratio = height / crop_height width_ratio = width / crop_width optimal_ratio = width_ratio if height_ratio < width_ratio: optimal_ratio = height_ratio optimal_size = (int(width / optimal_ratio), int(height / optimal_ratio)) img = img.resize(optimal_size) width, height = img.size left = (width - crop_width) / 2 top = (height - crop_height) / 2 right = (width + crop_width) / 2 bottom = (height + crop_height) / 2 img = img.crop((left, top, right, bottom)) img.save(path) def save_image(self, filename, image64): crop_path = os.path.join(Config.AVATAR_CLIENT_UPLOAD_FOLDER, filename) img = Image.open(BytesIO(base64.b64decode(image64))) self.crop_image(img, crop_path) if self.avatar: old = os.path.join(Config.AVATAR_CLIENT_UPLOAD_FOLDER, self.avatar) if os.path.exists(old): os.remove(old) self.avatar = filename class Admin(db.Model): id = db.Column(db.Integer, primary_key=True) role_id = db.Column(db.Integer, db.ForeignKey("role.id"), nullable=False) fullname = db.Column(EncryptedType(db.String, Config.SECRET_KEY, AesEngine, 'pkcs5'), nullable=False) email = db.Column(EncryptedType(db.String, Config.SECRET_KEY, AesEngine, 'pkcs5'), nullable=False) password_hash = db.Column(db.String(400), nullable=False) avatar = db.Column(EncryptedType(db.String, Config.SECRET_KEY, AesEngine, 'pkcs5')) created = db.Column(db.DateTime, default=datetime.utcnow) updated = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) user_id = db.Column(db.Integer, db.ForeignKey("user.id", ondelete='CASCADE')) def set_password(self, password): self.password_hash = generate_password_hash(password) def check_password(self, password): return check_password_hash(self.password_hash, password) @hybrid_property def avatar_url(self): return "/static/upload/images/avatars/admin/" + str(self.avatar) @staticmethod def crop_image(img, path): crop_height, crop_width = Config.AVATAR_CROP_SIZE width, height = img.size height_ratio = height / crop_height width_ratio = width / crop_width optimal_ratio = width_ratio if height_ratio < width_ratio: optimal_ratio = height_ratio optimal_size = (int(width / optimal_ratio), int(height / optimal_ratio)) img = img.resize(optimal_size) width, height = img.size left = (width - crop_width) / 2 top = (height - crop_height) / 2 right = (width + crop_width) / 2 bottom = (height + crop_height) / 2 img = img.crop((left, top, right, bottom)) img.save(path) def save_image(self, filename, image64): crop_path = os.path.join(Config.AVATAR_ADMIN_UPLOAD_FOLDER, filename) img = Image.open(BytesIO(base64.b64decode(image64))) self.crop_image(img, crop_path) if self.avatar: old = os.path.join(Config.AVATAR_ADMIN_UPLOAD_FOLDER, self.avatar) if os.path.exists(old): os.remove(old) self.avatar = filename class ClientFavourite(db.Model): id = db.Column(db.Integer, primary_key=True) product_id = db.Column(db.Integer, db.ForeignKey('product.id', ondelete='CASCADE'), nullable=False) client_id = db.Column(db.Integer, db.ForeignKey('client.id', ondelete='CASCADE'), nullable=False) created = db.Column(db.DateTime, default=datetime.utcnow) updated = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) client = db.relationship("Client", backref=db.backref("favourites", lazy=True, cascade="all,delete")) product = db.relationship("Product", backref=db.backref("favourites", lazy=True, cascade="all,delete")) class Role(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(100), nullable=False) description = db.Column(db.String(1000), nullable=False) created = db.Column(db.DateTime, default=datetime.utcnow) administrators = db.relationship( "Admin", cascade="all,delete", backref=db.backref("role", lazy=True), lazy=True ) class Category(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(255), nullable=False) link = db.Column(db.String(255), nullable=False) parent_id = db.Column(db.Integer, db.ForeignKey("category.id", ondelete='CASCADE')) created = db.Column(db.DateTime, default=datetime.utcnow) updated = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) parent = db.relationship( "Category", cascade="all,delete", backref=db.backref("children"), remote_side=id ) filters = db.relationship( 'Filter', secondary=category_filters, lazy='subquery', backref=db.backref('categories', lazy=True) ) @hybrid_property def products_length(self): return len(self.products) class Product(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(500), nullable=False) creator_id = db.Column(db.Integer, db.ForeignKey("creator.id", ondelete='CASCADE'), nullable=False) category_id = db.Column(db.Integer, db.ForeignKey("category.id", ondelete='CASCADE'), nullable=False) default_image_id = db.Column(db.Integer, db.ForeignKey('product_image.id', ondelete='SET NULL'), nullable=True) summary = db.Column(db.String(1000)) description = db.Column(db.Text) price = db.Column(db.Float, nullable=False) on_sale_price = db.Column(db.Float, nullable=True) condition = db.Column(db.String(100), nullable=False, default='new') stock = db.Column(db.Integer, default=0) on_sale = db.Column(db.Boolean, default=False) created = db.Column(db.DateTime, default=datetime.utcnow) updated = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) creator = db.relationship('Creator', backref=db.backref("products")) category = db.relationship('Category', backref=db.backref("direct_products")) default_image = db.relationship('ProductImage', foreign_keys=default_image_id, post_update=True) categories = db.relationship( 'Category', secondary=product_categories, lazy='subquery', backref=db.backref('products', lazy=True) ) filters = db.relationship( 'FilterValue', secondary=product_filters, lazy='subquery', backref=db.backref('products', lazy=True) ) @hybrid_property def reviews_length(self): return len(self.reviews) @hybrid_property def reviews_score(self): return ( sum( review.score for review in self.reviews ) / len(self.reviews) if self.reviews else 0 ) @hybrid_property def weighted_score(self): total_reviews = ProductReview.query.all() v = self.reviews_length r = self.reviews_score m = len(total_reviews) / Config.PERCENTAGE_OF_TOTAL_REVIEWS c = ( sum( review.score for review in total_reviews ) / len(total_reviews) if total_reviews else 0 ) return (r * v + c * m) / (v + m) class Creator(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(500), nullable=False) created = db.Column(db.DateTime, default=datetime.utcnow()) class Filter(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(500), nullable=False) created = db.Column(db.DateTime, default=datetime.utcnow()) class FilterValue(db.Model): id = db.Column(db.Integer, primary_key=True) filter_id = db.Column(db.Integer, db.ForeignKey('filter.id', ondelete='CASCADE'), nullable=False) value = db.Column(db.String(1000), nullable=False) created = db.Column(db.DateTime, default=datetime.utcnow()) filter = db.relationship( "Filter", cascade="all,delete", backref=db.backref("values") ) class ProductView(db.Model): id = db.Column(db.Integer, primary_key=True) product_id = db.Column(db.Integer, db.ForeignKey('product.id', ondelete='CASCADE'), nullable=False) client_id = db.Column(db.Integer, db.ForeignKey('client.id', ondelete='CASCADE'), nullable=True) client_ip = db.Column(db.String, nullable=False) created = db.Column(db.DateTime, default=datetime.utcnow) updated = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) product = db.relationship("Product", backref=db.backref("views", lazy=True, cascade="all,delete")) client = db.relationship("Client", backref=db.backref("views", lazy=True, cascade="all,delete")) class ProductImage(db.Model): id = db.Column(db.Integer, primary_key=True) product_id = db.Column(db.Integer, db.ForeignKey('product.id', ondelete='CASCADE'), nullable=False) image = db.Column(db.String(500), nullable=False) created = db.Column(db.DateTime, default=datetime.utcnow()) @hybrid_property def image_url(self): return "/static/upload/images/products/" + self.image @hybrid_property def thumb_url(self): return "/static/upload/images/products/thumbs/" + self.image @staticmethod def crop_image(img, path): crop_height, crop_width = Config.CROP_SIZE width, height = img.size height_ratio = height / crop_height width_ratio = width / crop_width optimal_ratio = width_ratio if height_ratio < width_ratio: optimal_ratio = height_ratio optimal_size = (int(width / optimal_ratio), int(height / optimal_ratio)) img = img.resize(optimal_size) width, height = img.size left = (width - crop_width) / 2 top = (height - crop_height) / 2 right = (width + crop_width) / 2 bottom = (height + crop_height) / 2 img = img.crop((left, top, right, bottom)) img.save(path) @staticmethod def resize_image(img, path, size): new_height, new_width = size width, height = img.size height_ratio = height / new_height width_ratio = width / new_width optimal_ratio = width_ratio if height_ratio < width_ratio: optimal_ratio = height_ratio optimal_size = (int(width / optimal_ratio), int(height / optimal_ratio)) img = img.resize(optimal_size) img.save(path) def save_image(self, filename, image64): path = os.path.join(Config.PRODUCT_UPLOAD_FOLDER, filename) crop_path = os.path.join(Config.PRODUCT_THUMB_UPLOAD_FOLDER, filename) img = Image.open(BytesIO(base64.b64decode(image64))) self.resize_image(img, path, Config.IMAGE_SIZE) self.resize_image(img, crop_path, Config.CROP_SIZE) self.image = filename class ProductReview(db.Model): id = db.Column(db.Integer, primary_key=True) client_id = db.Column(db.Integer, db.ForeignKey('client.id', ondelete='CASCADE'), nullable=False) product_id = db.Column(db.Integer, db.ForeignKey('product.id', ondelete='CASCADE'), nullable=False) score = db.Column(db.Integer, nullable=False) review = db.Column(db.Text, nullable=False) created = db.Column(db.DateTime, default=datetime.utcnow()) updated = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) product = db.relationship("Product", backref=db.backref("reviews", lazy=True, cascade="all,delete")) client = db.relationship("Client", backref=db.backref("reviews", lazy=True, cascade="all,delete")) class Cart(db.Model): id = db.Column(db.Integer, primary_key=True) client_id = db.Column(db.Integer, db.ForeignKey('client.id'), nullable=False) complete = db.Column(db.Boolean, default=False) created = db.Column(db.DateTime, default=datetime.utcnow()) updated = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) client = db.relationship("Client", backref=db.backref("carts", lazy=True)) def cart_total(self): return ( sum( cart_item.price for cart_item in self.cart_items ) if self.cart_items else 0 ) class CartItem(db.Model): id = db.Column(db.Integer, primary_key=True) cart_id = db.Column(db.Integer, db.ForeignKey('cart.id', ondelete='CASCADE'), nullable=False) product_id = db.Column(db.Integer, db.ForeignKey('product.id'), nullable=False) price = db.Column(db.Float, nullable=False) unit_price = db.Column(db.Float, nullable=False) quantity = db.Column(db.Float, nullable=False) created = db.Column(db.DateTime, default=datetime.utcnow()) updated = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) product = db.relationship("Product", backref=db.backref("cart_items", lazy=True, cascade="all,delete")) cart = db.relationship("Cart", backref=db.backref("cart_items", lazy=True, cascade="all,delete")) class Order(db.Model): id = db.Column(db.Integer, primary_key=True) cart_id = db.Column(db.Integer, db.ForeignKey('cart.id', ondelete='CASCADE'), nullable=False) client_id = db.Column(db.Integer, db.ForeignKey('client.id', ondelete='CASCADE'), nullable=False) address_id = db.Column(db.Integer, db.ForeignKey('address.id', ondelete='CASCADE')) store_address_id = db.Column(db.Integer, db.ForeignKey('store_address.id', ondelete='CASCADE')) price = db.Column(db.Float, nullable=False) reference = db.Column(db.String(1000)) payment_type = db.Column(db.String(30)) paid = db.Column(db.Boolean, default=False) shipping = db.Column(db.Boolean, default=True) status = db.Column(db.Integer, default=0) created = db.Column(db.DateTime, default=datetime.utcnow()) updated = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) address = db.relationship("Address", backref=db.backref("orders", lazy=True)) store_address = db.relationship("StoreAddress", backref=db.backref("orders", lazy=True)) client = db.relationship("Client", backref=db.backref("orders", lazy=True, cascade="all,delete")) cart = db.relationship("Cart", backref=db.backref("orders", lazy=True)) @hybrid_property def payment_type_string(self): return 'Online by card' if self.payment_type == 'online' else 'Payment upon receipt' @hybrid_property def shipping_string(self): return 'Delivery ' if self.shipping else 'Pick up from Store' @hybrid_property def status_string(self): statuses = ['PROCESSING', 'READY', 'COMPLETED', 'CANCELLED'] return statuses[self.status] class Address(db.Model): id = db.Column(db.Integer, primary_key=True) client_id = db.Column(db.Integer, db.ForeignKey('client.id', ondelete='CASCADE'), nullable=False) country_id = db.Column(db.Integer, db.ForeignKey('country.id', ondelete='CASCADE'), nullable=False) state = db.Column(db.String(255), nullable=False) city = db.Column(db.String(255), nullable=False) address = db.Column(db.String(500), nullable=False) postal_code = db.Column(db.String(10)) created = db.Column(db.DateTime, default=datetime.utcnow()) updated = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) client = db.relationship("Client", backref=db.backref("addresses", lazy=True, cascade="all,delete")) country = db.relationship("Country", backref=db.backref("addresses", lazy=True, cascade="all,delete")) class Country(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) short = db.Column(db.String(10)) created = db.Column(db.DateTime, default=datetime.utcnow()) updated = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) class StoreAddress(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) address = db.Column(db.String(255), nullable=False) phone = db.Column(db.String(100), nullable=False) iframe = db.Column(db.Text, nullable=False) opened = db.Column(db.Text, nullable=False) created = db.Column(db.DateTime, default=datetime.utcnow()) updated = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) class HomeCarousel(db.Model): id = db.Column(db.Integer, primary_key=True) type = db.Column(db.String(100), nullable=False) category_id = db.Column(db.Integer, db.ForeignKey("category.id"), nullable=False) created = db.Column(db.DateTime, default=datetime.utcnow()) class BannerImage(db.Model): id = db.Column(db.Integer, primary_key=True) image = db.Column(db.String(300), nullable=False) caption = db.Column(db.String(300)) active = db.Column(db.Boolean, default=False) created = db.Column(db.DateTime, default=datetime.utcnow()) updated = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow) @hybrid_property def image_url(self): return "/static/upload/images/banners/" + self.image @hybrid_property def thumb_url(self): return "/static/upload/images/banners/thumbs/" + self.image @staticmethod def resize_image(img, path, size): new_height, new_width = size width, height = img.size height_ratio = height / new_height width_ratio = width / new_width optimal_ratio = width_ratio if height_ratio < width_ratio: optimal_ratio = height_ratio optimal_size = (int(width / optimal_ratio), int(height / optimal_ratio)) img = img.resize(optimal_size) img.save(path) def save_image(self, filename, image64): path = os.path.join(Config.BANNER_UPLOAD_FOLDER, filename) crop_path = os.path.join(Config.BANNER_THUMB_UPLOAD_FOLDER, filename) img = Image.open(BytesIO(base64.b64decode(image64))) self.resize_image(img, path, Config.BANNER_SIZE) self.resize_image(img, crop_path, Config.CROP_SIZE) self.image = filename @event.listens_for(ProductImage, 'after_delete') def delete_image(mapper, connection, target): old = os.path.join(Config.PRODUCT_UPLOAD_FOLDER, target.image) if os.path.exists(old): os.remove(old) old = os.path.join(Config.PRODUCT_THUMB_UPLOAD_FOLDER, target.image) if os.path.exists(old): os.remove(old) @event.listens_for(BannerImage, 'after_delete') def delete_banner_image(mapper, connection, target): old = os.path.join(Config.BANNER_UPLOAD_FOLDER, target.image) if os.path.exists(old): os.remove(old) old = os.path.join(Config.BANNER_THUMB_UPLOAD_FOLDER, target.image) if os.path.exists(old): os.remove(old)
{"/app/models.py": ["/config.py"], "/app/schemas.py": ["/app/models.py"], "/app/api/routes.py": ["/app/schemas.py"]}
70,041
Dsthdragon/kizito_bookstore
refs/heads/master
/migrations/versions/76ef7c78ee7f_added_homecarousel_table.py
"""Added HomeCarousel Table Revision ID: 76ef7c78ee7f Revises: c1ffdaeef3ae Create Date: 2020-02-12 12:06:28.983755 """ from alembic import op import sqlalchemy as sa import sqlalchemy_utils # revision identifiers, used by Alembic. revision = '76ef7c78ee7f' down_revision = 'c1ffdaeef3ae' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('home_carousel', sa.Column('id', sa.Integer(), nullable=False), sa.Column('type', sa.String(length=100), nullable=False), sa.Column('category_id', sa.Integer(), nullable=False), sa.Column('created', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['category_id'], ['category.id'], ), sa.PrimaryKeyConstraint('id') ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('home_carousel') # ### end Alembic commands ###
{"/app/models.py": ["/config.py"], "/app/schemas.py": ["/app/models.py"], "/app/api/routes.py": ["/app/schemas.py"]}
70,042
Dsthdragon/kizito_bookstore
refs/heads/master
/migrations/versions/bcc08ae9bed7_added_client_favourite_and_product_views.py
"""added Client Favourite and product views Revision ID: bcc08ae9bed7 Revises: 399549c08a2a Create Date: 2020-01-24 22:55:04.098191 """ from alembic import op import sqlalchemy as sa import sqlalchemy_utils # revision identifiers, used by Alembic. revision = 'bcc08ae9bed7' down_revision = '399549c08a2a' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('client_favourite', sa.Column('id', sa.Integer(), nullable=False), sa.Column('product_id', sa.Integer(), nullable=False), sa.Column('client_id', sa.Integer(), nullable=False), sa.Column('created', sa.DateTime(), nullable=True), sa.Column('updated', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['client_id'], ['client.id'], ), sa.ForeignKeyConstraint(['product_id'], ['product.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_table('product_view', sa.Column('id', sa.Integer(), nullable=False), sa.Column('product_id', sa.Integer(), nullable=False), sa.Column('client_id', sa.Integer(), nullable=True), sa.Column('client_ip', sa.Integer(), nullable=False), sa.Column('created', sa.DateTime(), nullable=True), sa.Column('updated', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['client_id'], ['client.id'], ), sa.ForeignKeyConstraint(['client_ip'], ['product.id'], ), sa.ForeignKeyConstraint(['product_id'], ['product.id'], ), sa.PrimaryKeyConstraint('id') ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('product_view') op.drop_table('client_favourite') # ### end Alembic commands ###
{"/app/models.py": ["/config.py"], "/app/schemas.py": ["/app/models.py"], "/app/api/routes.py": ["/app/schemas.py"]}
70,043
Dsthdragon/kizito_bookstore
refs/heads/master
/app/schemas.py
from app import ma from app.models import * from marshmallow import fields class UserSchema(ma.TableSchema): class Meta: table = User.__table__ class ClientSchema(ma.TableSchema): class Meta: table = Client.__table__ user_id = fields.Int() favourites = fields.Nested('ClientFavouriteSchema', many=True) views = fields.Nested('ProductViewSchema', many=True) avatar_url = fields.String() class ClientFavouriteSchema(ma.TableSchema): class Meta: table = ClientFavourite.__table__ class AdminSchema(ma.TableSchema): class Meta: table = Admin.__table__ user_id = fields.Int() role_id = fields.Int() role = fields.Nested('RoleSchema', only=["title", "description"]) avatar_url = fields.String() class RoleSchema(ma.TableSchema): class Meta: table = Role.__table__ class CategorySchema(ma.TableSchema): class Meta: table = Category.__table__ children = fields.Nested('CategorySchema', many=True, only=["id", "title", "link", "products_length"]) parent = fields.Nested('CategorySchema', only=["id", "title", "link", "products_length"]) products_length = fields.Integer() class ProductSchema(ma.TableSchema): class Meta: table = Product.__table__ category = fields.Nested('CategorySchema', only=["id", "title", "link", "parent"]) creator = fields.Nested('CreatorSchema') default_image = fields.Nested('ProductImageSchema') categories = fields.Nested('CategorySchema', many=True, only=["id", "title", "link"]) filters = fields.Nested('FilterValueSchema', many=True, only=["id", "value", 'filter']) reviews_score = fields.Number() reviews_length = fields.Number() weighted_score = fields.Number() class ProductReviewSchema(ma.TableSchema): class Meta: table = ProductReview.__table__ client = fields.Nested('ClientSchema', only=["first_name", "last_name"]) product = fields.Nested('ProductSchema', only=["id", "default_image", "name"]) class ProductViewSchema(ma.TableSchema): class Meta: table = ProductView.__table__ class CreatorSchema(ma.TableSchema): class Meta: table = Creator.__table__ class FilterSchema(ma.TableSchema): class Meta: table = Filter.__table__ class FilterValueSchema(ma.TableSchema): class Meta: table = FilterValue.__table__ filter = fields.Nested('FilterSchema', only=["id", "title"]) class ProductImageSchema(ma.TableSchema): class Meta: table = ProductImage.__table__ image_url = fields.String() thumb_url = fields.String() class CartSchema(ma.TableSchema): class Meta: table = Cart.__table__ class CartItemSchema(ma.TableSchema): class Meta: table = CartItem.__table__ product = fields.Nested('ProductSchema', only=["id", "default_image", "name", "category"]) class OrderSchema(ma.TableSchema): class Meta: table = Order.__table__ payment_type_string = fields.String() shipping_string = fields.String() status_string = fields.String() address = fields.Nested('AddressSchema') store_address = fields.Nested('StoreAddressSchema') cart = fields.Nested('CartSchema') client = fields.Nested('ClientSchema', exclude=['favourites', 'views']) class AddressSchema(ma.TableSchema): class Meta: table = Address.__table__ country = fields.Nested('CountrySchema', only=["id", "name", "short"]) class CountrySchema(ma.TableSchema): class Meta: table = Country.__table__ class BannerImageSchema(ma.TableSchema): class Meta: table = BannerImage.__table__ image_url = fields.String() thumb_url = fields.String() class HomeCarouselSchema(ma.TableSchema): class Meta: table = HomeCarousel.__table__ class StoreAddressSchema(ma.TableSchema): class Meta: table = StoreAddress.__table__
{"/app/models.py": ["/config.py"], "/app/schemas.py": ["/app/models.py"], "/app/api/routes.py": ["/app/schemas.py"]}
70,044
Dsthdragon/kizito_bookstore
refs/heads/master
/migrations/versions/02e4548ac30e_added_default_image_id_discount_and_on_.py
"""Added default_image_id, discount and on_sale to Product table Revision ID: 02e4548ac30e Revises: cb4cef38cc2b Create Date: 2019-11-04 10:14:17.366883 """ from alembic import op import sqlalchemy as sa import sqlalchemy_utils # revision identifiers, used by Alembic. revision = '02e4548ac30e' down_revision = 'cb4cef38cc2b' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('product', sa.Column('default_image_id', sa.Integer(), nullable=True)) op.add_column('product', sa.Column('discount', sa.Float(), nullable=True)) op.add_column('product', sa.Column('on_sale', sa.Boolean(), nullable=True)) op.create_foreign_key(None, 'product', 'product_image', ['default_image_id'], ['id']) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_constraint(None, 'product', type_='foreignkey') op.drop_column('product', 'on_sale') op.drop_column('product', 'discount') op.drop_column('product', 'default_image_id') # ### end Alembic commands ###
{"/app/models.py": ["/config.py"], "/app/schemas.py": ["/app/models.py"], "/app/api/routes.py": ["/app/schemas.py"]}
70,045
Dsthdragon/kizito_bookstore
refs/heads/master
/migrations/versions/d5404c3f0892_added_columns_to_product_table.py
"""Added Columns to product table Revision ID: d5404c3f0892 Revises: e46758f4374f Create Date: 2019-11-10 08:38:56.864426 """ from alembic import op import sqlalchemy as sa import sqlalchemy_utils from sqlalchemy.dialects import mysql # revision identifiers, used by Alembic. revision = 'd5404c3f0892' down_revision = 'e46758f4374f' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('product', sa.Column('condition', sa.String(length=100), nullable=False)) op.add_column('product', sa.Column('on_sale_price', sa.Float(), nullable=True)) op.add_column('product', sa.Column('stock', sa.Integer(), nullable=True)) op.drop_column('product', 'discount') # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('product', sa.Column('discount', mysql.FLOAT(), nullable=True)) op.drop_column('product', 'stock') op.drop_column('product', 'on_sale_price') op.drop_column('product', 'condition') # ### end Alembic commands ###
{"/app/models.py": ["/config.py"], "/app/schemas.py": ["/app/models.py"], "/app/api/routes.py": ["/app/schemas.py"]}
70,046
Dsthdragon/kizito_bookstore
refs/heads/master
/migrations/versions/399549c08a2a_created_category_filters_and_product_.py
"""created category_filters and product_filters table Revision ID: 399549c08a2a Revises: cd94e2a90b09 Create Date: 2019-11-13 22:05:12.208403 """ from alembic import op import sqlalchemy as sa import sqlalchemy_utils from sqlalchemy.dialects import mysql # revision identifiers, used by Alembic. revision = '399549c08a2a' down_revision = 'cd94e2a90b09' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('category_filters', sa.Column('filter_id', sa.Integer(), nullable=False), sa.Column('category_id', sa.Integer(), nullable=False), sa.ForeignKeyConstraint(['category_id'], ['category.id'], ), sa.ForeignKeyConstraint(['filter_id'], ['filter.id'], ), sa.PrimaryKeyConstraint('filter_id', 'category_id') ) op.drop_table('category_filter') op.drop_table('product_filter') op.drop_constraint('product_filters_ibfk_1', 'product_filters', type_='foreignkey') op.drop_column('product_filters', 'filter_id') # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('product_filters', sa.Column('filter_id', mysql.INTEGER(display_width=11), autoincrement=False, nullable=False)) op.create_foreign_key('product_filters_ibfk_1', 'product_filters', 'filter', ['filter_id'], ['id']) op.create_table('product_filter', sa.Column('id', mysql.INTEGER(display_width=11), autoincrement=True, nullable=False), sa.Column('product_id', mysql.INTEGER(display_width=11), autoincrement=False, nullable=False), sa.Column('value_id', mysql.INTEGER(display_width=11), autoincrement=False, nullable=False), sa.Column('filter_id', mysql.INTEGER(display_width=11), autoincrement=False, nullable=False), sa.ForeignKeyConstraint(['filter_id'], ['filter.id'], name='product_filter_ibfk_1'), sa.ForeignKeyConstraint(['product_id'], ['product.id'], name='product_filter_ibfk_2'), sa.ForeignKeyConstraint(['value_id'], ['filter_value.id'], name='product_filter_ibfk_3'), sa.PrimaryKeyConstraint('id'), mysql_default_charset='latin1', mysql_engine='InnoDB' ) op.create_table('category_filter', sa.Column('id', mysql.INTEGER(display_width=11), autoincrement=True, nullable=False), sa.Column('category_id', mysql.INTEGER(display_width=11), autoincrement=False, nullable=False), sa.Column('filter_id', mysql.INTEGER(display_width=11), autoincrement=False, nullable=False), sa.Column('created', mysql.DATETIME(), nullable=True), sa.ForeignKeyConstraint(['category_id'], ['category.id'], name='category_filter_ibfk_1'), sa.ForeignKeyConstraint(['filter_id'], ['filter.id'], name='category_filter_ibfk_2'), sa.PrimaryKeyConstraint('id'), mysql_default_charset='latin1', mysql_engine='InnoDB' ) op.drop_table('category_filters') # ### end Alembic commands ###
{"/app/models.py": ["/config.py"], "/app/schemas.py": ["/app/models.py"], "/app/api/routes.py": ["/app/schemas.py"]}
70,047
Dsthdragon/kizito_bookstore
refs/heads/master
/migrations/versions/cd94e2a90b09_changed_product_categories.py
"""Changed product_categories ..... Revision ID: cd94e2a90b09 Revises: d5404c3f0892 Create Date: 2019-11-11 23:43:53.019145 """ from alembic import op import sqlalchemy as sa import sqlalchemy_utils from sqlalchemy.dialects import mysql # revision identifiers, used by Alembic. revision = 'cd94e2a90b09' down_revision = 'd5404c3f0892' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('product_categories', sa.Column('category_id', sa.Integer(), nullable=False), sa.Column('product_id', sa.Integer(), nullable=False), sa.ForeignKeyConstraint(['category_id'], ['category.id'], ), sa.ForeignKeyConstraint(['product_id'], ['product.id'], ), sa.PrimaryKeyConstraint('category_id', 'product_id') ) op.create_table('product_filters', sa.Column('filter_id', sa.Integer(), nullable=False), sa.Column('value_id', sa.Integer(), nullable=False), sa.Column('product_id', sa.Integer(), nullable=False), sa.ForeignKeyConstraint(['filter_id'], ['filter.id'], ), sa.ForeignKeyConstraint(['product_id'], ['product.id'], ), sa.ForeignKeyConstraint(['value_id'], ['filter_value.id'], ), sa.PrimaryKeyConstraint('filter_id', 'value_id', 'product_id') ) op.drop_table('category_product') # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('category_product', sa.Column('id', mysql.INTEGER(display_width=11), autoincrement=True, nullable=False), sa.Column('category_id', mysql.INTEGER(display_width=11), autoincrement=False, nullable=False), sa.Column('product_id', mysql.INTEGER(display_width=11), autoincrement=False, nullable=False), sa.ForeignKeyConstraint(['category_id'], ['category.id'], name='category_product_ibfk_1'), sa.ForeignKeyConstraint(['product_id'], ['product.id'], name='category_product_ibfk_2'), sa.PrimaryKeyConstraint('id'), mysql_default_charset='latin1', mysql_engine='InnoDB' ) op.drop_table('product_filters') op.drop_table('product_categories') # ### end Alembic commands ###
{"/app/models.py": ["/config.py"], "/app/schemas.py": ["/app/models.py"], "/app/api/routes.py": ["/app/schemas.py"]}
70,048
Dsthdragon/kizito_bookstore
refs/heads/master
/config.py
import os class Config(object): SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or 'mysql://root:''@localhost/kizito_bookstore' SQLALCHEMY_TRACK_MODIFICATIONS = False PAYSTACK_SECRET_KEY = os.environ.get('PAYSTACK_SECRET_KEY') or 'sk_test_ea5f84af6fdf29d466ca49c8920216ad9567d9e1'; POSTS_PER_PAGE = 10 SECRET_KEY = os.environ.get('SECRET_KEY') or "kizito_secret_key" AVATAR_ADMIN_UPLOAD_FOLDER = os.path.abspath( os.path.join("app", "static", "upload", "images", "avatars", "admin") ) AVATAR_CLIENT_UPLOAD_FOLDER = os.path.abspath( os.path.join("app", "static", "upload", "images", "avatars", "client") ) PRODUCT_UPLOAD_FOLDER = os.path.abspath( os.path.join("app", "static", "upload", "images", "products") ) PRODUCT_THUMB_UPLOAD_FOLDER = os.path.abspath( os.path.join("app", "static", "upload", "images", "products", "thumbs") ) BANNER_UPLOAD_FOLDER = os.path.abspath( os.path.join("app", "static", "upload", "images", "banners") ) BANNER_THUMB_UPLOAD_FOLDER = os.path.abspath( os.path.join("app", "static", "upload", "images", "banners", "thumbs") ) PRODUCT_IMAGE_URL = ("/static", "upload", "images", "products") PRODUCT_THUMB_URL = ("/static", "upload", "images", "products", "thumbs") BANNER_IMAGE_URL = ("/static", "upload", "images", "banners") BANNER_THUMB_URL = ("/static", "upload", "images", "banners", "thumbs") IMAGE_SIZE = [500, 500] CROP_SIZE = [200, 200] AVATAR_CROP_SIZE = [100, 100] BANNER_SIZE = [1280, 400] PERCENTAGE_OF_TOTAL_REVIEWS = 10
{"/app/models.py": ["/config.py"], "/app/schemas.py": ["/app/models.py"], "/app/api/routes.py": ["/app/schemas.py"]}
70,049
Dsthdragon/kizito_bookstore
refs/heads/master
/migrations/versions/c0401ab3f0e4_added_delete_casade_foreign_keys.py
"""added delete casade foreign keys Revision ID: c0401ab3f0e4 Revises: 76ef7c78ee7f Create Date: 2020-02-18 16:40:06.184355 """ from alembic import op import sqlalchemy as sa import sqlalchemy_utils # revision identifiers, used by Alembic. revision = 'c0401ab3f0e4' down_revision = '76ef7c78ee7f' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_constraint('address_ibfk_1', 'address', type_='foreignkey') op.drop_constraint('address_ibfk_2', 'address', type_='foreignkey') op.create_foreign_key(None, 'address', 'client', ['client_id'], ['id'], ondelete='CASCADE') op.create_foreign_key(None, 'address', 'country', ['country_id'], ['id'], ondelete='CASCADE') op.drop_constraint('admin_ibfk_2', 'admin', type_='foreignkey') op.create_foreign_key(None, 'admin', 'user', ['user_id'], ['id'], ondelete='CASCADE') op.drop_constraint('cart_item_ibfk_1', 'cart_item', type_='foreignkey') op.create_foreign_key(None, 'cart_item', 'cart', ['cart_id'], ['id'], ondelete='CASCADE') op.drop_constraint('category_ibfk_1', 'category', type_='foreignkey') op.create_foreign_key(None, 'category', 'category', ['parent_id'], ['id'], ondelete='CASCADE') op.drop_constraint('client_ibfk_1', 'client', type_='foreignkey') op.create_foreign_key(None, 'client', 'user', ['user_id'], ['id'], ondelete='CASCADE') op.drop_constraint('client_favourite_ibfk_2', 'client_favourite', type_='foreignkey') op.drop_constraint('client_favourite_ibfk_1', 'client_favourite', type_='foreignkey') op.create_foreign_key(None, 'client_favourite', 'product', ['product_id'], ['id'], ondelete='CASCADE') op.create_foreign_key(None, 'client_favourite', 'client', ['client_id'], ['id'], ondelete='CASCADE') op.drop_constraint('filter_value_ibfk_1', 'filter_value', type_='foreignkey') op.create_foreign_key(None, 'filter_value', 'filter', ['filter_id'], ['id'], ondelete='CASCADE') op.drop_constraint('order_ibfk_3', 'order', type_='foreignkey') op.drop_constraint('order_ibfk_2', 'order', type_='foreignkey') op.drop_constraint('order_ibfk_1', 'order', type_='foreignkey') op.create_foreign_key(None, 'order', 'address', ['address_id'], ['id'], ondelete='CASCADE') op.create_foreign_key(None, 'order', 'client', ['client_id'], ['id'], ondelete='CASCADE') op.create_foreign_key(None, 'order', 'cart', ['cart_id'], ['id'], ondelete='CASCADE') op.drop_constraint('product_ibfk_1', 'product', type_='foreignkey') op.drop_constraint('product_ibfk_2', 'product', type_='foreignkey') op.create_foreign_key(None, 'product', 'creator', ['creator_id'], ['id'], ondelete='CASCADE') op.create_foreign_key(None, 'product', 'category', ['category_id'], ['id'], ondelete='CASCADE') op.drop_constraint('product_image_ibfk_1', 'product_image', type_='foreignkey') op.create_foreign_key(None, 'product_image', 'product', ['product_id'], ['id'], ondelete='CASCADE') op.drop_constraint('product_review_ibfk_1', 'product_review', type_='foreignkey') op.drop_constraint('product_review_ibfk_2', 'product_review', type_='foreignkey') op.create_foreign_key(None, 'product_review', 'client', ['client_id'], ['id'], ondelete='CASCADE') op.create_foreign_key(None, 'product_review', 'product', ['product_id'], ['id'], ondelete='CASCADE') op.drop_constraint('product_view_ibfk_3', 'product_view', type_='foreignkey') op.drop_constraint('product_view_ibfk_1', 'product_view', type_='foreignkey') op.create_foreign_key(None, 'product_view', 'product', ['product_id'], ['id'], ondelete='CASCADE') op.create_foreign_key(None, 'product_view', 'client', ['client_id'], ['id'], ondelete='CASCADE') # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_constraint(None, 'product_view', type_='foreignkey') op.drop_constraint(None, 'product_view', type_='foreignkey') op.create_foreign_key('product_view_ibfk_1', 'product_view', 'client', ['client_id'], ['id']) op.create_foreign_key('product_view_ibfk_3', 'product_view', 'product', ['product_id'], ['id']) op.drop_constraint(None, 'product_review', type_='foreignkey') op.drop_constraint(None, 'product_review', type_='foreignkey') op.create_foreign_key('product_review_ibfk_2', 'product_review', 'product', ['product_id'], ['id']) op.create_foreign_key('product_review_ibfk_1', 'product_review', 'client', ['client_id'], ['id']) op.drop_constraint(None, 'product_image', type_='foreignkey') op.create_foreign_key('product_image_ibfk_1', 'product_image', 'product', ['product_id'], ['id']) op.drop_constraint(None, 'product', type_='foreignkey') op.drop_constraint(None, 'product', type_='foreignkey') op.create_foreign_key('product_ibfk_2', 'product', 'creator', ['creator_id'], ['id']) op.create_foreign_key('product_ibfk_1', 'product', 'category', ['category_id'], ['id']) op.drop_constraint(None, 'order', type_='foreignkey') op.drop_constraint(None, 'order', type_='foreignkey') op.drop_constraint(None, 'order', type_='foreignkey') op.create_foreign_key('order_ibfk_1', 'order', 'address', ['address_id'], ['id']) op.create_foreign_key('order_ibfk_2', 'order', 'cart', ['cart_id'], ['id']) op.create_foreign_key('order_ibfk_3', 'order', 'client', ['client_id'], ['id']) op.drop_constraint(None, 'filter_value', type_='foreignkey') op.create_foreign_key('filter_value_ibfk_1', 'filter_value', 'filter', ['filter_id'], ['id']) op.drop_constraint(None, 'client_favourite', type_='foreignkey') op.drop_constraint(None, 'client_favourite', type_='foreignkey') op.create_foreign_key('client_favourite_ibfk_1', 'client_favourite', 'client', ['client_id'], ['id']) op.create_foreign_key('client_favourite_ibfk_2', 'client_favourite', 'product', ['product_id'], ['id']) op.drop_constraint(None, 'client', type_='foreignkey') op.create_foreign_key('client_ibfk_1', 'client', 'user', ['user_id'], ['id']) op.drop_constraint(None, 'category', type_='foreignkey') op.create_foreign_key('category_ibfk_1', 'category', 'category', ['parent_id'], ['id']) op.drop_constraint(None, 'cart_item', type_='foreignkey') op.create_foreign_key('cart_item_ibfk_1', 'cart_item', 'cart', ['cart_id'], ['id']) op.drop_constraint(None, 'admin', type_='foreignkey') op.create_foreign_key('admin_ibfk_2', 'admin', 'user', ['user_id'], ['id']) op.drop_constraint(None, 'address', type_='foreignkey') op.drop_constraint(None, 'address', type_='foreignkey') op.create_foreign_key('address_ibfk_2', 'address', 'country', ['country_id'], ['id']) op.create_foreign_key('address_ibfk_1', 'address', 'client', ['client_id'], ['id']) # ### end Alembic commands ###
{"/app/models.py": ["/config.py"], "/app/schemas.py": ["/app/models.py"], "/app/api/routes.py": ["/app/schemas.py"]}
70,050
Dsthdragon/kizito_bookstore
refs/heads/master
/migrations/versions/cb4cef38cc2b_change_column_name_to_title_in_category_.py
"""Change column name to title in Category table Revision ID: cb4cef38cc2b Revises: 95b2f50b1799 Create Date: 2019-11-01 09:51:17.114489 """ from alembic import op import sqlalchemy as sa import sqlalchemy_utils from sqlalchemy.dialects import mysql # revision identifiers, used by Alembic. revision = 'cb4cef38cc2b' down_revision = '95b2f50b1799' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('category', sa.Column('title', sa.String(length=255), nullable=False)) op.drop_column('category', 'name') # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('category', sa.Column('name', mysql.VARCHAR(length=255), nullable=False)) op.drop_column('category', 'title') # ### end Alembic commands ###
{"/app/models.py": ["/config.py"], "/app/schemas.py": ["/app/models.py"], "/app/api/routes.py": ["/app/schemas.py"]}
70,051
Dsthdragon/kizito_bookstore
refs/heads/master
/migrations/versions/c1ffdaeef3ae_added_bannerimage_table_and_.py
"""Added BannerImage Table and StoreAddress Table Revision ID: c1ffdaeef3ae Revises: bcc08ae9bed7 Create Date: 2020-02-11 16:52:10.442005 """ from alembic import op import sqlalchemy as sa import sqlalchemy_utils # revision identifiers, used by Alembic. revision = 'c1ffdaeef3ae' down_revision = 'bcc08ae9bed7' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('banner_image', sa.Column('id', sa.Integer(), nullable=False), sa.Column('image', sa.String(length=300), nullable=False), sa.Column('caption', sa.String(length=300), nullable=True), sa.Column('active', sa.Boolean(), nullable=True), sa.Column('created', sa.DateTime(), nullable=True), sa.Column('updated', sa.DateTime(), nullable=True), sa.PrimaryKeyConstraint('id') ) op.create_table('store_address', sa.Column('id', sa.Integer(), nullable=False), sa.Column('address', sa.String(length=255), nullable=False), sa.Column('phone', sa.String(length=100), nullable=False), sa.Column('iframe', sa.Text(), nullable=False), sa.Column('opened', sa.Text(), nullable=False), sa.Column('created', sa.DateTime(), nullable=True), sa.Column('updated', sa.DateTime(), nullable=True), sa.PrimaryKeyConstraint('id') ) op.drop_constraint('product_view_ibfk_2', 'product_view', type_='foreignkey') # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_foreign_key('product_view_ibfk_2', 'product_view', 'product', ['client_ip'], ['id']) op.drop_table('store_address') op.drop_table('banner_image') # ### end Alembic commands ###
{"/app/models.py": ["/config.py"], "/app/schemas.py": ["/app/models.py"], "/app/api/routes.py": ["/app/schemas.py"]}
70,052
Dsthdragon/kizito_bookstore
refs/heads/master
/app/api/routes.py
from flask import jsonify, request, current_app, make_response from sqlalchemy import or_ from functools import wraps from app.api import bp from app.schemas import * from app import db import uuid import random import requests ALLOWED_EXTENSIONS = ['png', 'jpeg', 'jpg', 'gif'] def login_required(f): @wraps(f) def wrap(*args, **kwargs): user_id = User.decode_token(request.cookies.get('auth')) user = User.query.get(user_id) if not user: return jsonify(status="failed", message="Login to continue", isAuth=False) return f(*args, **kwargs) return wrap # Auth endpoint @bp.route('/auth') def user_auth(): user_id = User.decode_token(request.cookies.get('auth')) user = User.query.get(user_id) if not user: return jsonify(status="failed", message="Invalid token received", isAuth=False) client = ClientSchema().dump(user.client) is_client = True if user.client else False admin = AdminSchema().dump(user.admin) is_admin = True if user.admin else False return jsonify(status="success", message="User Logged In", isAuth=True, client=client, admin=admin, isClient=is_client, isAdmin=is_admin) # Roles endpoints @bp.route("/roles") def get_roles(): role_model = Role.query.all() role_schema = RoleSchema(many=True).dump(role_model) return jsonify(status="success", message="Roles Found", data=role_schema) @bp.route("/roles", methods=['POST']) def create_roles(): data = request.get_json() if not data: jsonify(status="failed", message="No Data Sent") if not data.get('title'): jsonify(status="failed", message="Title required!") if not data.get('description'): jsonify(status="failed", message="Description required!") role_model = Role.query.filter_by(title=data['title']).first() if role_model: return jsonify(status="failed", message="Role already in system!") role_model = Role(title=data['title'], description=data['description']) db.session.add(role_model) db.session.commit() return jsonify(status="success", message="Role Created!") @bp.route('/roles/<role_id>', methods=['DELETE']) def delete_role(_id): role_model = Role.query.get(int(_id)) if not role_model: return jsonify(status="failed", message="Role not found in system") db.session.delete(role_model) db.session.commit() return jsonify(status="success", message="Role Deleted successfully") @bp.route('/roles/<role_id>') def get_role(role_id): role_model = Role.query.get(int(role_id)) if not role_model: return jsonify(status="failed", message="Role not found in system") role_schema = RoleSchema().dump(role_model) return jsonify(status="success", message="Role Found", data=role_schema) # Administrators Endpoints @bp.route('/administrator/login', methods=['POST']) def login_administrator(): data = request.get_json() if not data: return jsonify(status='failed', message="No data sent!") admin_model = Admin.query.filter_by(email=data.get('email')).first() if admin_model and admin_model.check_password(data.get('password')): resp = make_response(jsonify(status="success", message="Login Successful!")) resp.set_cookie('auth', admin_model.user.generate_token()) return resp return jsonify(status='failed', message='Invalid email/password') @bp.route('/administrator') def get_administrators(): limited = request.args.get('limited', 1, type=int) if limited: page = request.args.get("page", 1, type=int) admin_model = Admin.query.paginate(page, current_app.config['POSTS_PER_PAGE'], False) has_next = admin_model.has_next admin_model = admin_model.items else: admin_model = Admin.query.all() has_next = False admin_schema = AdminSchema(many=True).dump(admin_model) return jsonify(status="success", message="Administrators Found", data=admin_schema, has_next=has_next) @bp.route('/administrator', methods=['POST']) def create_administrator(): data = request.get_json() if not data: return jsonify(status='failed', message='No Data sent!') if not data.get('fullname'): return jsonify(status='failed', message="Full Name required!") if not data.get('email'): return jsonify(status='failed', message="Email address required!") if not data.get('password'): return jsonify(status='failed', message="Password required!") admin_model = Admin.query.filter_by(email=data.get('email')).first() if admin_model: return jsonify(status='failed', message='Email Already in system') role_model = Role.query.get(data.get('role')) if not role_model: return jsonify(status='failed', message='Role Not Found') user_model = User() admin_model = Admin() admin_model.user = user_model admin_model.email = data.get('email') admin_model.role_id = data.get('role') admin_model.fullname = data.get('fullname') admin_model.set_password(data.get('password')) db.session.add_all([user_model, admin_model]) db.session.commit() resp = make_response(jsonify(status="success", message="Admin Created!")) resp.set_cookie('auth', admin_model.user.generate_token()) return resp @bp.route('/administrator/<int:admin_id>', methods=['PUT']) @login_required def update_admin(admin_id): data = request.get_json() if not data: return jsonify(status='failed', message='No Data sent!') if not data.get('fullname'): return jsonify(status='failed', message="Full Name required!") if not data.get('email'): return jsonify(status='failed', message="Email required!") admin_model = Admin.query.get(admin_id) if not admin_model: return jsonify(status='failed', message='Admin Not Found') admin_model.full_name = data.get('fullname') admin_model.email = data.get('email') db.session.commit() admin_schema = AdminSchema().dump(admin_model) return jsonify(status='success', message='Admin Update', data=admin_schema) @bp.route('/administrator/change_password/<int:admin_id>', methods=['PUT']) @login_required def change_admin_password(admin_id): data = request.get_json() if not data: return jsonify(status='failed', message='No Data sent!') if not data.get('password'): return jsonify(status='failed', message="Password is required!") if not data.get('new_password'): return jsonify(status='failed', message="New Password is required!") admin_model = Admin.query.get(admin_id) if not admin_model: return jsonify(status='failed', message='Client Not Found') if not admin_model.check_password(data.get('password')): return jsonify(status='failed', message='Invalid Password') admin_model.set_password(data.get('new_password')) db.session.commit() admin_schema = ClientSchema().dump(admin_model) return jsonify(status='success', message='Admin Password Update', data=admin_schema) @bp.route('/administrator/<int:admin_id>/avatar', methods=['PUT']) def upload_admin_avatar(admin_id): data = request.get_json() if not data: return jsonify(status="failed", message="No Data Sent!") if not data.get('type'): return jsonify(status="failed", message="Image type required!") if not data.get('img'): return jsonify(status="failed", message="Image data not sent!") if data.get('type').lower() not in ALLOWED_EXTENSIONS: return jsonify(status="failed", message="Extension not supported!") admin_model = Admin.query.get(admin_id) if not admin_model: return jsonify(status='failed', message='Admin Not Found') unique_filename = str(uuid.uuid4()) + '.' + data['type'].lower() admin_model.save_image(unique_filename, data['img']) db.session.commit() admin_schema = AdminSchema().dump(admin_model) return jsonify(status='success', message='Avatar uploaded', data=admin_schema) @bp.route('/administrator/<admin_id>') def get_administrator(admin_id): admin_model = Admin.query.get(admin_id) if not admin_model: return jsonify(status="failed", message="Admin not found in system") admin_schema = AdminSchema().dump(admin_model) return jsonify(status="success", message="Role Found", data=admin_schema) # Category endpoint @bp.route('/category') def get_categories(): limited = request.args.get('limited', 1, type=int) if limited: page = request.args.get("page", 1, type=int) category_model = Category.query.order_by(Category.parent_id.asc()).paginate(page, current_app.config[ 'POSTS_PER_PAGE'], False) has_next = category_model.has_next category_model = category_model.items else: category_model = Category.query.order_by(Category.parent_id.asc()).all() has_next = False category_schema = CategorySchema(many=True).dump(category_model) return jsonify(status="success", message="Categories Found", data=category_schema, has_next=has_next) @bp.route('/category/parent/<category_id>') def get_category_by_parent(category_id): parent = category_id if int(category_id) > 0 else None category_model = Category.query.filter_by(parent_id=parent).all() category_schema = CategorySchema(many=True).dump(category_model) return jsonify(status="success", message="Categories Found", data=category_schema) @bp.route('/category', methods=['POST']) def create_category(): data = request.get_json() if not data: return jsonify(status='failed', message='No data sent!') if not data.get('title'): return jsonify(status='failed', message='Title required!') title = str(data.get('title')) category_model = Category.query.filter_by(title=title).first() if category_model: return jsonify(status='failed', message='Category already in system!') category_model = Category() category_model.title = title category_model.link = (title.replace(' ', '_') + "_" + str(random.randint(100, 100000))).lower() if data.get('parent'): category_model.parent_id = data.get('parent') db.session.add(category_model) db.session.commit() return jsonify(status='success', message='Category Created!') @bp.route('/category/<string:link>') def get_category_by_link(link): category_model = Category.query.filter_by(link=link).first() if not category_model: return jsonify(status='failed', message="Category Not Found") category_schema = CategorySchema().dump(category_model) return jsonify(status='success', message='Category Found', data=category_schema) @bp.route('/category/<int:category_id>') def get_category_by_id(category_id): category_model = Category.query.get(category_id) if not category_model: return jsonify(status='failed', message="Category Not Found") category_schema = CategorySchema().dump(category_model) return jsonify(status='success', message='Category Found', data=category_schema) @bp.route('/category/<category_id>', methods=['DELETE']) def delete_category(category_id): category_model = Category.query.get(category_id) if not category_model: return jsonify(status='failed', message="Category Not Found") db.session.delete(category_model) db.session.commit() return jsonify(status='success', message='Category Deleted') @bp.route('/category/product/<int:product_id>') def get_unassociated_product_categories(product_id): category_model = Category.query.filter(~Category.products.any(Product.id == product_id)) category_schema = CategorySchema(many=True).dump(category_model) return jsonify(status='success', message='Category Found', data=category_schema) # Product Endpoint @bp.route('/product') def get_products(): order_by = request.args.get("order_by", "created", type=str) order = request.args.get("order", 'desc', type=str) limited = request.args.get('limited', 1, type=int) product_model = Product.query if order == 'desc': product_model = product_model.order_by(getattr(Product, order_by).desc()) else: product_model = product_model.order_by(getattr(Product, order_by).asc()) if limited: page = request.args.get("page", 1, type=int) product_model = product_model.paginate(page, current_app.config['POSTS_PER_PAGE'], False) has_next = product_model.has_next product_model = product_model.items else: product_model = product_model.all() has_next = False product_schema = ProductSchema(many=True).dump(product_model) return jsonify(status="success", message="Products Found", data=product_schema, has_next=has_next) @bp.route('/product/filter/<int:product_id>', methods=['POST']) def add_filter_product(product_id): data = request.get_json() if not data: return jsonify(status='failed', message='No data sent') product_model = Product.query.get(product_id) if not product_model: return jsonify(status='failed', message='Product not Found') for filter_data in data: filter_value_model = FilterValue.query.filter_by( filter_id=filter_data['id'], value=filter_data['value'] ).first() if not filter_value_model: filter_value_model = FilterValue(filter_id=filter_data['id'], value=filter_data['value']) db.session.add(filter_value_model) product_model.filters.append(filter_value_model) db.session.commit() return jsonify(status='success', message='Filter Added To Product') @bp.route('/product/filter/<int:product_id>/<int:filter_id>', methods=['DELETE']) def delete_filter_product(product_id, filter_id): product_model = Product.query.get(product_id) if not product_model: return jsonify(status='failed', message='Product not Found!') filter_value_model = FilterValue.query.get(filter_id) if not product_model: return jsonify(status='failed', message='Filter not Found!') product_model.filters.remove(filter_value_model) db.session.commit() return jsonify(status='success', message='Filter Removed From Product') @bp.route('/product/category/<int:product_id>', methods=['POST']) def add_category_product(product_id): data = request.get_json() if not data: return jsonify(status='failed', message='No data sent') if not data.get('category'): return jsonify(status='failed', message='Category Required') product_model = Product.query.get(product_id) if not product_model: return jsonify(status='failed', message='Product not Found') for x in data.get('category'): category_model = Category.query.get(x) while category_model: if category_model: product_model.categories.append(category_model) if category_model.parent_id: category_model = Category.query.category_model(category_model.parent_id) else: category_model = None db.session.commit() return jsonify(status='success', message='Category Added') @bp.route('/product/category/<int:product_id>/<int:category_id>', methods=['DELETE']) def delete_category_product(product_id, category_id): product_model = Product.query.get(product_id) if not product_model: return jsonify(status='failed', message='Product not Found!') category_model = Category.query.get(category_id) if not category_model: return jsonify(status='failed', message='Category not Found!') product_model.categories.remove(category_model) db.session.commit() return jsonify(status='success', message='Category Removed Deleted') @bp.route('/product/category/<int:category_id>') def get_products_by_category(category_id): limited = request.args.get('limited', 1, type=int) if limited: page = request.args.get("page", 1, type=int) product_model = Product.query.filter(Product.categories.any(Category.id == category_id)) product_model = product_model.paginate(page, current_app.config['POSTS_PER_PAGE'], False) has_next = product_model.has_next product_model = product_model.items else: product_model = Product.query.all() has_next = False product_schema = ProductSchema(many=True).dump(product_model) return jsonify(status="success", message="Products Found", data=product_schema, has_next=has_next) @bp.route('/find_products') def find_products(): title = request.args.get("title", "", type=str) category = request.args.get("category", None, type=int) order_by = request.args.get("order_by", "created", type=str) order = request.args.get("order", 'desc', type=str) page = request.args.get("page", 1, type=int) per_page = request.args.get("per_page", 0, type=int) per_page = per_page if per_page != 0 else current_app.config['POSTS_PER_PAGE'] product_model = Product.query if title: product_model = product_model.filter( or_( Product.name.ilike(f"%{title}%"), Product.description.ilike(f"{title}%"), Product.summary.ilike(f"%{title}%"), Product.creator.has(Creator.title.ilike(f"%{title}%")) ) ) if category: product_model = product_model.filter(Product.categories.any(Category.id == category)) if order == 'desc': product_model = product_model.order_by(getattr(Product, order_by).desc()) else: product_model = product_model.order_by(getattr(Product, order_by).asc()) product_model = product_model.paginate(page, per_page, False) has_next = product_model.has_next total = product_model.total product_model = product_model.items product_schema = ProductSchema(many=True).dump(product_model) return jsonify(status="success", message="product_model Found", data=product_schema, has_next=has_next, total=total) @bp.route('/product/<product_id>') def get_product(product_id): product_model = Product.query.get(product_id) if not product_model: return jsonify(status='failed', message="Product Not Found") product_schema = ProductSchema().dump(product_model) return jsonify(status='success', message="Product Found", data=product_schema) @bp.route('/product/<product_id>', methods=['DELETE']) def delete_product(product_id): product_model = Product.query.get(product_id) if not product_model: return jsonify(status='failed', message="Product Not Found") db.session.delete(product_model) db.session.commit() return jsonify(status='success', message="Product Deleted", ) @bp.route('/product', methods=['POST']) def create_product(): data = request.get_json() if not data: return jsonify(status='failed', message='No data sent') if not data.get('creator'): return jsonify(status='failed', message='Creator Required') creator_model = Creator.query.filter_by(title=str(data.get('creator')).lower()).first() if not creator_model: creator_model = Creator(title=str(data.get('creator')).lower()) db.session.add(creator_model) db.session.commit() if not data.get('name'): return jsonify(status='failed', message='Name Required!') if not data.get('category'): return jsonify(status='failed', message='Category Required!') if not data.get('price'): return jsonify(status='failed', message='Price Required!') if not data.get('summary'): return jsonify(status='failed', message='Summary Required!') if not data.get('description'): return jsonify(status='failed', message='description Required!') product_model = Product() product_model.category_id = data.get('category') product_model.price = data.get('price') product_model.name = data.get('name') product_model.creator = creator_model product_model.description = data.get('description') product_model.summary = data.get('summary') category_model = Category.query.get(data.get('category')) while category_model: if category_model: product_model.categories.append(category_model) if category_model.parent_id: category_model = Category.query.get(category_model.parent_id) else: category_model = None db.session.add(product_model) db.session.commit() product_schema = ProductSchema().dump(product_model) return jsonify(status='success', message='Product Created', data=product_schema) @bp.route('/product/<product_id>', methods=['PUT']) def update_product(product_id): product_model = Product.query.get(product_id) if not product_model: return jsonify(status='failed', message="Product not Found") data = request.get_json() if not data: return jsonify(status='failed', message="No Data sent") for d in data: setattr(product_model, d, data[d]) db.session.commit() return jsonify(status='success', message="Update Successful") # Product Images Endpoint @bp.route('/image', methods=['POST']) def upload_image(): data = request.get_json() if not data: return jsonify(status="failed", message="No Data Sent!") product_model = Product.query.get(data.get('id')) if not product_model: return jsonify(status="failed", message="Product Not Found") if not data.get('type'): return jsonify(status="failed", message="Image type required!") if not data.get('img'): return jsonify(status="failed", message="Image data not sent!") if data.get('type').lower() not in ALLOWED_EXTENSIONS: return jsonify(status="failed", message="Extension not supported!") unique_filename = str(uuid.uuid4()) + '.' + data['type'].lower() product_image_model = ProductImage() product_image_model.save_image(unique_filename, data['img']) product_image_model.product_id = product_model.id if not product_model.default_image_id: product_model.default_image = product_image_model db.session.add(product_image_model) db.session.commit() return jsonify(status='success', message='Image uploaded') @bp.route('/image/<product_id>') def get_product_images(product_id): product_image_model = ProductImage.query.filter_by(product_id=product_id).all() product_image_schema = ProductImageSchema(many=True).dump(product_image_model) return jsonify(status="success", message="Product Images Found", data=product_image_schema) @bp.route('/image/<product_image_id>', methods=['DELETE']) def delete_image(product_image_id): product_image_model = ProductImage.query.get(product_image_id) if not product_image_model: return jsonify(status='failed', message='Product Image not found') db.session.delete(product_image_model) db.session.commit() return jsonify(status='failed', message='Product Image Deleted') @bp.route('/image/<product_image_id>', methods=['PUT']) def change_main(product_image_id): product_image_model = ProductImage.query.get(product_image_id) if not product_image_model: return jsonify(status='success', message='Product Image not found!') product_model = Product.query.get(product_image_model.product_id) if not product_model: return jsonify(status='success', message='Product Image found!') product_model.default_image = product_image_model db.session.commit() return jsonify(status='success', message='Product Made Main') # Filters Endpoint @bp.route('/filter') def get_filters(): limited = request.args.get('limited', 1, type=int) if limited: page = request.args.get("page", 1, type=int) filter_model = Filter.query.paginate(page, current_app.config['POSTS_PER_PAGE'], False) has_next = filter_model.has_next filter_model = filter_model.items else: filter_model = Filter.query.all() has_next = False filter_schema = FilterSchema(many=True).dump(filter_model) return jsonify(status="success", message="Filters Found", data=filter_schema, has_next=has_next) @bp.route('/filter', methods=['POST']) def create_filter(): data = request.get_json() if not data: return jsonify(status='failed', message='Data Required!') if not data.get('title'): return jsonify(status='failed', message='Filter Title Required!') title = data.get('title') filter_model = Filter.query.filter_by(title=title).first() if filter_model: return jsonify(status='failed', message='Filter Already in System!') filter_model = Filter(title=title) db.session.add(filter_model) db.session.commit() return jsonify(status='success', message='Filter Added To System') @bp.route('/filter/<int:filter_id>') def get_filter(filter_id): filter_model = Filter.query.get(filter_id) if not filter_model: return jsonify(status='failed', message='Filter Not Found') filter_schema = FilterSchema().dump(filter_model) return jsonify(status='success', message='Filter Found', data=filter_schema) @bp.route('/filter/<int:filter_id>', methods=['DELETE']) def delete_filter(filter_id): filter_model = Filter.query.get(filter_id) if not filter_model: return jsonify(status='failed', message='Filter Not Found') db.session.delete(filter_model) db.session.commit() return jsonify(status='success', message='Filter Deleted') @bp.route('/filter/product/<int:product_id>') def get_unassociated_product_filter(product_id): filter_model = Filter.query.filter(~Filter.values.any(FilterValue.products.any(Product.id == product_id))) filter_schema = FilterSchema(many=True).dump(filter_model) return jsonify(status='success', message='Filters Found Found', data=filter_schema) # Clients routes @bp.route('/client/login', methods=['POST']) def login_client(): data = request.get_json() if not data: return jsonify(status='failed', message="No data sent!") client_model = Client.query.filter_by(email=data.get('email')).first() if client_model and client_model.check_password(data.get('password')): resp = make_response(jsonify(status="success", message="Login Successful!")) resp.set_cookie('auth', client_model.user.generate_token()) return resp return jsonify(status='failed', message='Invalid email/password') @bp.route('/client', methods=['POST']) def register_client(): data = request.get_json() if not data: return jsonify(status='failed', message='No Data sent!') if not data.get('first_name'): return jsonify(status='failed', message="First Name required!") if not data.get('email'): return jsonify(status='failed', message="Email address required!") if not data.get('password'): return jsonify(status='failed', message="Password required!") client_model = Client.query.filter_by(email=data.get('email')).first() if client_model: return jsonify(status='failed', message='Email Already in system') user_model = User() client_model = Client() client_model.user = user_model client_model.email = data.get('email') client_model.phone = data.get('phone') client_model.first_name = data.get('first_name') client_model.last_name = data.get('last_name') client_model.set_password(data.get('password')) db.session.add_all([user_model, client_model]) db.session.commit() resp = make_response(jsonify(status="success", message="Client Created!")) resp.set_cookie('auth', client_model.user.generate_token()) return resp @bp.route('/client/<int:client_id>', methods=['PUT']) @login_required def update_client(client_id): data = request.get_json() if not data: return jsonify(status='failed', message='No Data sent!') if not data.get('first_name'): return jsonify(status='failed', message="First Name required!") client_model = Client.query.get(client_id) if not client_model: return jsonify(status='failed', message='Client Not Found') client_model.first_name = data.get('first_name') client_model.last_name = data.get('last_name') client_model.phone = data.get('phone') db.session.commit() client_schema = ClientSchema().dump(client_model) return jsonify(status='success', message='Client Update', data=client_schema) @bp.route('/client/change_password/<int:client_id>', methods=['PUT']) @login_required def change_password(client_id): data = request.get_json() if not data: return jsonify(status='failed', message='No Data sent!') if not data.get('password'): return jsonify(status='failed', message="Password is required!") if not data.get('new_password'): return jsonify(status='failed', message="New Password is required!") client_model = Client.query.get(client_id) if not client_model: return jsonify(status='failed', message='Client Not Found') if not client_model.check_password(data.get('password')): return jsonify(status='failed', message='Invalid Password') client_model.set_password(data.get('new_password')) db.session.commit() client_schema = ClientSchema().dump(client_model) return jsonify(status='success', message='Client Password Update', data=client_schema) @bp.route('/client/<int:client_id>') def get_client(client_id): client_model = Client.query.get(client_id) if not client_model: return jsonify(status='failed', message='Client Not Found') client_schema = ClientSchema().dump(client_model) return jsonify(status='success', message='Client Found', data=client_schema) @bp.route('/client/<int:client_id>/avatar', methods=['PUT']) def upload_client_avatar(client_id): data = request.get_json() if not data: return jsonify(status="failed", message="No Data Sent!") if not data.get('type'): return jsonify(status="failed", message="Image type required!") if not data.get('img'): return jsonify(status="failed", message="Image data not sent!") if data.get('type').lower() not in ALLOWED_EXTENSIONS: return jsonify(status="failed", message="Extension not supported!") client_model = Client.query.get(client_id) if not client_model: return jsonify(status='failed', message='Client Not Found') unique_filename = str(uuid.uuid4()) + '.' + data['type'].lower() client_model.save_image(unique_filename, data['img']) db.session.commit() client_schema = ClientSchema().dump(client_model) return jsonify(status='success', message='Avatar uploaded', data=client_schema) @bp.route('/logout') def logout_user(): resp = make_response(jsonify(status="success", message="Logout Successful!")) resp.set_cookie('auth', '') return resp @bp.route('/product/favourite', methods=['POST']) @login_required def add_favourite(): data = request.get_json() if not data: return jsonify(status='failed', message='No Data sent!') client_model = Client.query.get(data.get('client')) if not client_model: return jsonify(status='failed', message='Client not found!') product_model = Product.query.get(data.get('product')) if not product_model: return jsonify(status='failed', message='product not found!') client_favourite = ClientFavourite.query.filter_by( client_id=client_model.id, product_id=product_model.id ).first() if client_favourite: return jsonify(status='failed', message='Product already favourite!') client_favourite = ClientFavourite() client_favourite.client_id = client_model.id client_favourite.product_id = product_model.id db.session.add(client_favourite) db.session.commit() return jsonify(status='success', message='Product added to favourite!') @bp.route('/product/favourite/<int:product_id>/<int:client_id>', methods=['DELETE']) @login_required def remove_favourite(product_id, client_id): client_favourite = ClientFavourite.query.filter_by( client_id=client_id, product_id=product_id ).first() if client_favourite: db.session.delete(client_favourite) db.session.commit() return jsonify(status='success', message='Product remove from favourite!') @bp.route('/client/favourite/<int:client_id>') def get_user_favourite(client_id): page = request.args.get("page", 1, type=int) per_page = request.args.get("per_page", 0, type=int) per_page = per_page if per_page != 0 else current_app.config['POSTS_PER_PAGE'] product_model = Product.query.filter( Product.favourites.any(ClientFavourite.client_id == client_id) ) product_model = product_model.paginate(page, per_page, False) has_next = product_model.has_next total = product_model.total product_model = product_model.items product_schema = ProductSchema(many=True).dump(product_model) return jsonify(status="success", message="Products Found!", data=product_schema, has_next=has_next, total=total) @bp.route('/product/review', methods=['POST']) @login_required def product_review(): data = request.get_json() if not data: return jsonify(status='failed', message='No Data sent!') client_model = Client.query.get(data.get('client')) if not client_model: return jsonify(status='failed', message='Client not found!') product_model = Product.query.get(data.get('product')) if not product_model: return jsonify(status='failed', message='Product not found!') if not data.get('review'): return jsonify(status='failed', message='Review Required!') if not data.get('score'): return jsonify(status='failed', message='Score Required!') product_review_model = ProductReview.query.filter_by(product_id=product_model.id, client_id=client_model.id).first() if product_review_model: return jsonify(status='failed', message='Client Already Reviewed product!') product_review_model = ProductReview() product_review_model.client = client_model product_review_model.product = product_model product_review_model.score = data.get('score') product_review_model.review = data.get('review') db.session.add(product_review_model) db.session.commit() return jsonify(status='success', message='Product reviewed!') @bp.route('/product/review/<int:product_id>') def product_reviews(product_id): product_review_model = ProductReview.query.filter_by(product_id=product_id).all() product_review_schema = ProductReviewSchema(many=True).dump(product_review_model) return jsonify(status="success", message="Products Reviews Found!", data=product_review_schema) # Cart routes @bp.route('/cart/add', methods=["POST"]) @login_required def add_to_cart(): data = request.get_json() if not data: return jsonify(status="failed", message="No data sent") product_model = Product.query.get(data.get('product')) if not product_model: return jsonify(status="failed", message="Product not found") cart_model = Cart.query.get(data.get('cart')) if not cart_model: client_model = Client.query.get(data.get('client')) if not client_model: return jsonify(status="failed", message="Client not found") cart_model = Cart.query.filter_by(client_id=client_model.id,complete=False).first() if not cart_model: cart_model = Cart() cart_model.client = client_model db.session.add(cart_model) db.session.commit() cart_item_model = CartItem.query.filter_by(cart_id=cart_model.id, product_id=product_model.id).first() if cart_item_model: cart_item_model.quantity += data.get('quantity') cart_item_model.price = cart_item_model.unit_price * cart_item_model.quantity else: cart_item_model = CartItem() cart_item_model.product = product_model cart_item_model.cart = cart_model cart_item_model.unit_price = product_model.on_sale_price if product_model.on_sale else product_model.price cart_item_model.quantity = data.get('quantity') cart_item_model.price = cart_item_model.unit_price * cart_item_model.quantity db.session.add(cart_item_model) db.session.commit() if cart_item_model.quantity <= 0: db.session.delete(cart_item_model) db.session.commit() cart_schema = CartSchema().dump(cart_model) return jsonify(status="success", message="Cart Updated", data=cart_schema) @bp.route('/cart/products/<int:cart_id>') def cart_products(cart_id): cart_item_model = CartItem.query.filter_by(cart_id=cart_id).all() cart_item_schema = CartItemSchema(many=True).dump(cart_item_model) return jsonify(status="success", message="Cart Items Found!", data=cart_item_schema) @bp.route('/cart/remove/<int:cart_item_id>') @login_required def cart_remove_item(cart_item_id): cart_item_model = CartItem.query.get(cart_item_id) db.session.delete(cart_item_model) db.session.commit() return jsonify(status="success", message="Cart Items Removed!") # Product Images Endpoint @bp.route('/banner', methods=['POST']) def upload_banner(): data = request.get_json() if not data: return jsonify(status="failed", message="No Data Sent!") if not data.get('type'): return jsonify(status="failed", message="Image type required!") if not data.get('img'): return jsonify(status="failed", message="Image data not sent!") if data.get('type').lower() not in ALLOWED_EXTENSIONS: return jsonify(status="failed", message="Extension not supported!") unique_filename = str(uuid.uuid4()) + '.' + data['type'].lower() banner_image_model = BannerImage() banner_image_model.save_image(unique_filename, data['img']) db.session.add(banner_image_model) db.session.commit() return jsonify(status='success', message='Banner uploaded') @bp.route('/banner') def get_banners(): banner_image_model = BannerImage.query.all() banner_image_schema = BannerImageSchema(many=True).dump(banner_image_model) return jsonify(status="success", message="Banner Found!", data=banner_image_schema) @bp.route('/active_banners') def get_active_banners(): banner_image_model = BannerImage.query.filter_by(active=True).all() banner_image_schema = BannerImageSchema(many=True).dump(banner_image_model) return jsonify(status="success", message="Banner Found!", data=banner_image_schema) @bp.route('/banner/<banner_image_id>', methods=['DELETE']) def delete_banner(banner_image_id): banner_image_model = BannerImage.query.get(banner_image_id) if not banner_image_model: return jsonify(status='failed', message='Banner Image not found') db.session.delete(banner_image_model) db.session.commit() return jsonify(status='failed', message='Banner Image Deleted') @bp.route('/banner/<banner_image_id>', methods=['PUT']) def toggle_banner(banner_image_id): banner_image_model = BannerImage.query.get(banner_image_id) if not banner_image_model: return jsonify(status='success', message='Product Image not found!') banner_image_model.active = not banner_image_model.active db.session.commit() return jsonify(status='success', message='Product Visibility Update') @bp.route('/home_carousel') def get_home_carousels(): home_carousel_model = HomeCarousel.query.all() home_carousel_schema = HomeCarouselSchema(many=True).dump(home_carousel_model) return jsonify(status='success', message='Home Carousels found', data=home_carousel_schema) # Country @bp.route("/country") def get_countries(): country_model = Country.query.all() country_schema = CountrySchema(many=True).dump(country_model) return jsonify(status="success", message="Country Found!", data=country_schema) # add addresss @bp.route("/address") def get_address(): address_model = Address.query.all() address_schema = AddressSchema(many=True).dump(address_model) return jsonify(status="success", message="Address Found!", data=address_schema) @bp.route("/address/<int:client_id>") def get_client_address(client_id): address_model = Address.query.filter_by(client_id=client_id).all() address_schema = AddressSchema(many=True).dump(address_model) return jsonify(status="success", message="Address Found!", data=address_schema) @bp.route("/address", methods=['POST']) def create_client_address(): data = request.get_json() if not data: return jsonify(status="failed", message="No Data Sent!") if not data.get('client_id'): return jsonify(status="failed", message="Client Id required!") if not data.get('country_id'): return jsonify(status="failed", message="Country Id required!") if not data.get('state'): return jsonify(status="failed", message="State required!") if not data.get('city'): return jsonify(status="failed", message="City required!") if not data.get('address'): return jsonify(status="failed", message="Address required!") address = Address() address.client_id = data.get('client_id') address.country_id = data.get('country_id') address.state = data.get('state') address.city = data.get('city') address.address = data.get('address') address.postal_code = data.get('postal_code') db.session.add(address) db.session.commit() return jsonify(status="success", message="Address Added") @bp.route("/checkout", methods=["POST"]) def checkout(): data = request.get_json() if not data: return jsonify(status="failed", message="No Data Sent!") cart_model = Cart.query.get(data.get('cart_id')) if not cart_model: return jsonify(status="failed", message="Cart Id Required!") elif cart_model.complete == 1: return jsonify(status="failed", message="Cart Already Checkout!") client_model = Client.query.get(data.get('client_id')) if not client_model: return jsonify(status="failed", message="Client Id Required!") if not data.get('payment_type'): return jsonify(status="failed", message="Payment Type Required!") if data.get('shipping'): address = Address.query.get(data.get('address_id')) if not address: return jsonify(status="failed", message="Address Required for shipping option!") else: store_address = StoreAddress.query.get(data.get('store_address_id')) if not store_address: return jsonify(status="failed", message="Pick store required!") order_model = Order() order_model.cart_id = cart_model.id order_model.client_id = client_model.id order_model.price = cart_model.cart_total() order_model.payment_type = data.get('payment_type') order_model.shipping = data.get('shipping') if data.get('shipping'): order_model.address_id = data.get('address_id') else: order_model.store_address_id = data.get('store_address_id') order_model.payment_type = data.get('payment_type') order_model.status = 0 cart_model.complete = 1 db.session.add(order_model) db.session.commit() order_schema = OrderSchema().dump(order_model) return jsonify(status="success", message="Order Created!", data=order_schema) @bp.route("/store_address", methods=['POST']) def create_store_address(): data = request.get_json() if not data: return jsonify(status="failed", message="No Data Sent!") if not data.get('name'): return jsonify(status="failed", message="Name Required!") if not data.get('address'): return jsonify(status="failed", message="Address Required!") if not data.get('phone'): return jsonify(status="failed", message="Phone Required!") if not data.get('iframe'): return jsonify(status="failed", message="Iframe Required!") if not data.get('opened'): return jsonify(status="failed", message="Opened Required!") store_address = StoreAddress() store_address.name = data.get('name') store_address.opened = data.get('opened') store_address.address = data.get('address') store_address.phone = data.get('phone') store_address.iframe = data.get('iframe') db.session.add(store_address) db.session.commit() return jsonify(status="success", message="Store Address Created!") @bp.route("/order/<order_id>") def get_order(order_id): order = Order.query.get(order_id) if not order: return jsonify(status="failed", message="Order Not found!") return jsonify(status="success", message="Order found!", data=OrderSchema().dump(order)) @bp.route('/order/verify_payment', methods=['POST']) def verify_payment(): data = request.get_json() if not data.get('ref'): return jsonify(status="failed", message="Payment reference required!") order = Order.query.get(data.get('order_id')) if not order: return jsonify(status="failed", message="Order Not found!") url = "https://api.paystack.co/transaction/verify/" + data['ref'] response = requests.get(url, headers={'Authorization': 'Bearer {}'.format(Config.PAYSTACK_SECRET_KEY)}) response = response.json() if response and response.get('data'): if response['data']['status'] == 'success': if float(response['data']['amount']) <= order.price * 100: order.reference = data['ref'] order.paid = 1 db.session.commit() return jsonify(status="success", message="Order found!", data=OrderSchema().dump(order)) return jsonify(status="failed", message="Wrong amount paid", ) return jsonify(status="failed", message=response['data']['message'], ) return jsonify(status="failed", message="Something Went Wrong") @bp.route("/client/order/<client_id>") def get_client_orders(client_id): orders = Order.query.filter_by(client_id=client_id).all() return jsonify( status="success", message="Client Orders Found!", data=OrderSchema(many=True).dump(orders) ) @bp.route("/order") def get_orders(): orders = Order.query.all() return jsonify( status="success", message="Orders Found!", data=OrderSchema(many=True).dump(orders) ) @bp.route("/store_address") def get_store_address(): store_address = StoreAddress.query.all() return jsonify( status="success", message="Store Addresses Found!", data=StoreAddressSchema(many=True).dump(store_address) )
{"/app/models.py": ["/config.py"], "/app/schemas.py": ["/app/models.py"], "/app/api/routes.py": ["/app/schemas.py"]}
70,053
Dsthdragon/kizito_bookstore
refs/heads/master
/migrations/versions/573eb06f3c5c_added_shipping_to_order.py
"""Added shipping to order Revision ID: 573eb06f3c5c Revises: c0401ab3f0e4 Create Date: 2020-03-17 00:15:30.666414 """ from alembic import op import sqlalchemy as sa import sqlalchemy_utils # revision identifiers, used by Alembic. revision = '573eb06f3c5c' down_revision = 'c0401ab3f0e4' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('order', sa.Column('shipping', sa.Boolean(), nullable=True)) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('order', 'shipping') # ### end Alembic commands ###
{"/app/models.py": ["/config.py"], "/app/schemas.py": ["/app/models.py"], "/app/api/routes.py": ["/app/schemas.py"]}
70,061
G-C62/echo_telegram
refs/heads/master
/api/echo.py
# -*- coding:utf-8 -*- from flask.blueprints import Blueprint from flask import url_for, redirect, request, g, flash from echo_telegram_base import dao, try_except, app from flask_login import current_user, login_required import telegram import schedule import datetime echo_api = Blueprint("echo_api", __name__) def start_event(category, name): # 참석자 및 등록한 사람 status 변경 with app.app_context(): insert_name = name if name != None else current_user.name cursor = dao.get_conn().cursor() cursor.execute('''update users set status = %s where name = %s;''', [category, insert_name]) return schedule.CancelJob @echo_api.route('/echo', methods=['POST']) @try_except @login_required def create_event(): #telegram bot 생성 channel = request.form['event_channel'].encode("utf-8") if 'event_channel' in request.form else '' chat_id = '@' + channel my_token = '679610515:AAFtEx0IjBlLQAobCva70CBrqgyYpOrcEDU' # 토큰을 설정해 줍니다. bot = telegram.Bot(token=my_token) # 봇을 생성합니다. category = request.form['event_category'].encode("utf-8") if 'event_category' in request.form else '' location = request.form['event_location'].encode("utf-8") if 'event_location' in request.form else '' subject = request.form['event_subject'].encode("utf-8") if 'event_subject' in request.form else '' attendants = request.form['event_attendants'].encode("utf-8") if 'event_attendants' in request.form else '' start = request.form['event_start'].encode("utf-8") if 'event_start' in request.form else '' query = '' print attendants.replace(' ', '') # status가 존재하는데 또 생성하려는 경우 방지 if current_user.status != 'place' and current_user.status is not None and category != 'notice': flash('자리에 돌아온 후 다시 시도해주세요') return redirect(url_for('dashboard_view.dashboard')) #start가 pm이면 12시간 더해주기 if 'PM' in start: hour = str(int(start[0:2])+12) minute = start[2:5] start = hour + minute cursor = dao.get_conn().cursor() #DB에 이벤트 insert if category == 'meeting': query = '''insert into events(category, place, subject, start_time, channel_id, user_id, attendants) values(%s, %s, %s, %s, %s, (select id from users where user_id = %s), %s)''' cursor.execute(query, [category, location, subject, start, current_user.channel, current_user.userId, attendants]) # bot.sendMessage(chat_id=chat_id, text='---- 회의 -----\n' + # '장소: ' + location + '\n' + # '주제: ' + subject + '\n' + # '참석자: ' + attendants + '\n' + # '시작시간: ' + start + '\n' + # '** 작성자 :' + current_user.name) # 메세지를 보냅니다. elif category == 'away' or category == 'outside': query = '''insert into events(category, subject, start_time, channel_id, user_id) values(%s, %s, %s, %s, (select id from users where user_id = %s))''' cursor.execute(query, [category, subject, start, current_user.channel, current_user.userId]) if category == 'away': pass # bot.sendMessage(chat_id=chat_id, text='---- 자리비움 -----\n' + # '사유: ' + subject + '\n' + # '시작시간: ' + start + '\n' + # '** 작성자 :' + current_user.name) # 메세지를 보냅니다. else: pass # bot.sendMessage(chat_id=chat_id, text='---- 외근 -----\n' + # '주제: ' + subject + '\n' + # '시작시간: ' + start + '\n' + # '** 작성자 :' + current_user.name) # 메세지를 보냅니다. elif category == 'notice': query = '''insert into events(category, channel_id, user_id, attendants, iscomplete) values(%s, %s, (select id from users where user_id = %s), %s, 1)''' cursor.execute(query, [category, current_user.channel, current_user.userId, attendants]) # bot.sendMessage(chat_id=chat_id, text='---- 공지 -----\n' + # attendants + '\n' + # '** 작성자 :' + current_user.name) # 메세지를 보냅니다. return redirect(url_for('dashboard_view.dashboard')) else: return redirect(url_for('dashboard_view.dashboard')) cursor.close() g.conn.commit() #schedule 걸어서 해당 시간되면 참석자 및 작성자 status변화 시키기 # 1. 현재시간보다 이전 시간인 경우 now = datetime.datetime.now() start_datetime = now.replace(hour=int(start[0:2]), minute=int(start[3:5])) if now >= start_datetime: if category == 'meeting': # 공백 또는 , 로 분할하여 리스트로만듦 attendants_list = attendants.replace(' ', '').split(',') if ',' in attendants else attendants.split(' ') # 참석자 수만큼 돌려서 update for i in range(len(attendants_list)): start_event(category, attendants_list[i]) start_event(category, current_user.name) # 2. 현재시간 이후인 경우 else: if category == 'meeting': # 공백 또는 , 로 분할하여 리스트로만듦 attendants_list = attendants.replace(' ', '').split(',') if ',' in attendants else attendants.split(' ') # 참석자 수만큼 돌려서 update for i in range(len(attendants_list)): schedule.every().day.at(start[0:5]).do(start_event, category=category, name=attendants_list[i]) schedule.every().day.at(start[0:5]).do(start_event, category=category, name=current_user.name) cursor.close() g.conn.commit() return redirect(url_for('dashboard_view.dashboard'))
{"/echo_telegram_base.py": ["/echo_telegram_conf.py", "/db/user.py", "/api/login.py", "/views/main.py", "/views/dashboard.py", "/api/signup.py", "/api/register_channel.py", "/api/user.py", "/api/echo.py"], "/api/register_channel.py": ["/echo_telegram_base.py"], "/views/dashboard.py": ["/echo_telegram_base.py"], "/api/user.py": ["/echo_telegram_base.py"], "/api/signup.py": ["/echo_telegram_base.py"], "/api/login.py": ["/echo_telegram_base.py", "/api/signup.py", "/db/user.py"]}
70,062
G-C62/echo_telegram
refs/heads/master
/db/user.py
# -*- coding: utf-8 -*- class User: def __init__(self, userId, name, rank, status, channel, location, auth=False): self.userId = userId self.name = name self.rank = rank self.status = status self.channel = channel self.location = location self.authenticated = auth def __repr__(self): r = { 'user_id': self.userId, 'name': self.name, 'rank': self.rank, 'status': self.status, 'channel': self.channel, 'location': self.location, 'authenticated': self.authenticated, } return str(r) def is_authenticated(self): '''user객체가 인증되었다면 True를 반환''' return self.authenticated def is_active(self): '''특정 계정의 활성화 여부, inactive 계정의 경우 로그인이 되지 않도록 설정할 수 있다.''' return True def is_anonymous(self): '''익명의 사용자로 로그인 할 때만 True반환''' return False def get_id(self): ''' - 사용자의 ID를 unicode로 반환 - user_loader 콜백 메소드에서 사용자 ID를 얻을 때 사용할 수도 있다. ''' return self.userId
{"/echo_telegram_base.py": ["/echo_telegram_conf.py", "/db/user.py", "/api/login.py", "/views/main.py", "/views/dashboard.py", "/api/signup.py", "/api/register_channel.py", "/api/user.py", "/api/echo.py"], "/api/register_channel.py": ["/echo_telegram_base.py"], "/views/dashboard.py": ["/echo_telegram_base.py"], "/api/user.py": ["/echo_telegram_base.py"], "/api/signup.py": ["/echo_telegram_base.py"], "/api/login.py": ["/echo_telegram_base.py", "/api/signup.py", "/db/user.py"]}
70,063
G-C62/echo_telegram
refs/heads/master
/echo_telegram_base.py
# -*- coding:utf-8 -*- import sys, os from flask import Flask, current_app from app_logger import logger from flask_session import Session from functools import wraps from flask.globals import g, request from datetime import datetime, timedelta from flask_login.login_manager import LoginManager import schedule import time from threading import Thread login_manager = LoginManager() login_manager.login_view = 'main_view.index' # 보안성 레벨 설정 login_manager.session_protection = 'strong' login_manager.login_message = '로그인이 필요함' reload(sys) sys.setdefaultencoding("utf-8") #flask 앱 생성 app = Flask(__name__) with app.app_context(): logger.info("app 생성----------") # 환경설정 파일들 경로 설정 from echo_telegram_conf import EchoTelegramConfig app.config.from_object(EchoTelegramConfig) logger.info(">>> app.confing : %s" % (str(app.config))) login_manager.init_app(app) logger.info("login_manager init----------------") #http 응답 끝날때 DB connection 닫기 @app.teardown_request def db_close(e): if hasattr(g,"conn"): #db_conntion이 있을 때만 close한다. #g.conn.commit() g.conn.close() logger.info( ">> db connection close - %s" % (g.conn)) # db 초기 설정값 입력 db_info = app.config['DB_USER']+':'+app.config['DB_PASSWD']+'@'+app.config['DB_HOST']+'/'+app.config['DB_SCHEMA']+'?charset=utf8' app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://' + db_info app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False session = Session(app) # session 유지 시간설정 app.permanent_session_lifetime = timedelta(days=31) # session 관리를 위한 테이블 자동생성 session.app.session_interface.db.create_all() # 사용자 정의 데코레이터 def try_except(f): @wraps(f) def deco_func(*args, **kwargs): try: return f(*args, **kwargs) except Exception as e: logger.info("\n\n\n############exception############") logger.info(str(e)) logger.info("#################################\n\n") raise e return deco_func # db 초기화 후 dao객체 얻어오기 from db.EchoTelegramDB import EchoTelegramDB db_url = 'mysql+pymysql://' + db_info dao = EchoTelegramDB(db_url) logger.info(">>> DB connection : %s" % (str(dao))) from db.user import User @login_manager.user_loader @try_except def load_user(userId): query = 'select user_id, name, rank, status, channel_id, seat_location from users where user_id = %s' cursor = dao.get_conn().cursor() cursor.execute(query, [userId]) current_user = cursor.fetchone() cursor.close() g.conn.commit() user = User(userId=current_user[0], name=current_user[1], rank=current_user[2], status=current_user[3], channel=current_user[4], location=current_user[5], auth=False) return user # blueprint 등록 from api.login import login_api from views.main import main_view from views.dashboard import dashboard_view from api.signup import signup_api from api.register_channel import register_channel_api from api.user import user_api from api.echo import echo_api app.register_blueprint(login_api) app.register_blueprint(main_view) app.register_blueprint(dashboard_view) app.register_blueprint(signup_api) app.register_blueprint(register_channel_api) app.register_blueprint(user_api, url_prefix='/user') app.register_blueprint(echo_api) # thread생성 def run_schedule(): while 1: schedule.run_pending() time.sleep(1) thread = Thread(target=run_schedule) thread.daemon = True thread.start() # 로그인 페이지 엔드포인트 logger.info(">>> Blueprint setting. ") logger.info("===========================================================")
{"/echo_telegram_base.py": ["/echo_telegram_conf.py", "/db/user.py", "/api/login.py", "/views/main.py", "/views/dashboard.py", "/api/signup.py", "/api/register_channel.py", "/api/user.py", "/api/echo.py"], "/api/register_channel.py": ["/echo_telegram_base.py"], "/views/dashboard.py": ["/echo_telegram_base.py"], "/api/user.py": ["/echo_telegram_base.py"], "/api/signup.py": ["/echo_telegram_base.py"], "/api/login.py": ["/echo_telegram_base.py", "/api/signup.py", "/db/user.py"]}
70,064
G-C62/echo_telegram
refs/heads/master
/api/register_channel.py
# -*- coding: utf-8 -*- from flask_login import login_required, current_user from flask import redirect, url_for, Blueprint, request, g from echo_telegram_base import dao register_channel_api = Blueprint("register_channel_api", __name__) def check_channel(channel): cursor = dao.get_conn().cursor() cursor.execute('''select * from channels where channel_name = %s''', [channel]) result = False if cursor.fetchone() is not None else True cursor.close() g.conn.commit() return result @register_channel_api.route('/register_channel') @login_required def register_channel(): # prompt로 보내온 채널ID를 DB에 등록 한 후 # 현재 유저의 채널로 설정 # 이후 dashboard로 다시 이동 channel_id = request.args.get("channel").encode("utf-8") cursor = dao.get_conn().cursor() if(check_channel(channel_id)): cursor.execute('''insert into channels values(null, %s);''', [channel_id]) cursor.execute('''update users set channel_id = (select id from channels where channel_name = %s) where user_id = %s;''', [channel_id, current_user.userId]) cursor.close() g.conn.commit() return redirect(url_for('dashboard_view.dashboard'))
{"/echo_telegram_base.py": ["/echo_telegram_conf.py", "/db/user.py", "/api/login.py", "/views/main.py", "/views/dashboard.py", "/api/signup.py", "/api/register_channel.py", "/api/user.py", "/api/echo.py"], "/api/register_channel.py": ["/echo_telegram_base.py"], "/views/dashboard.py": ["/echo_telegram_base.py"], "/api/user.py": ["/echo_telegram_base.py"], "/api/signup.py": ["/echo_telegram_base.py"], "/api/login.py": ["/echo_telegram_base.py", "/api/signup.py", "/db/user.py"]}
70,065
G-C62/echo_telegram
refs/heads/master
/echo_telegram_conf.py
# -*- coding: utf-8 -*- class EchoTelegramConfig(object): SECRET_KEY = "3PO-Echo" SESSION_SQLALCHEMY_TABLE = "sessions" SESSION_TYPE = "sqlalchemy" DB_USER = "root" DB_PASSWD = "webdev1!" DB_HOST = "10.10.1.175" DB_SCHEMA = "c62"
{"/echo_telegram_base.py": ["/echo_telegram_conf.py", "/db/user.py", "/api/login.py", "/views/main.py", "/views/dashboard.py", "/api/signup.py", "/api/register_channel.py", "/api/user.py", "/api/echo.py"], "/api/register_channel.py": ["/echo_telegram_base.py"], "/views/dashboard.py": ["/echo_telegram_base.py"], "/api/user.py": ["/echo_telegram_base.py"], "/api/signup.py": ["/echo_telegram_base.py"], "/api/login.py": ["/echo_telegram_base.py", "/api/signup.py", "/db/user.py"]}
70,066
G-C62/echo_telegram
refs/heads/master
/views/main.py
#-*- coding:utf-8 -*- from flask.templating import render_template from flask.blueprints import Blueprint main_view = Blueprint("main_view", __name__) @main_view.route("/") def index(): return render_template("index.html")
{"/echo_telegram_base.py": ["/echo_telegram_conf.py", "/db/user.py", "/api/login.py", "/views/main.py", "/views/dashboard.py", "/api/signup.py", "/api/register_channel.py", "/api/user.py", "/api/echo.py"], "/api/register_channel.py": ["/echo_telegram_base.py"], "/views/dashboard.py": ["/echo_telegram_base.py"], "/api/user.py": ["/echo_telegram_base.py"], "/api/signup.py": ["/echo_telegram_base.py"], "/api/login.py": ["/echo_telegram_base.py", "/api/signup.py", "/db/user.py"]}
70,067
G-C62/echo_telegram
refs/heads/master
/views/dashboard.py
# -*- coding:utf-8 -*- from flask.blueprints import Blueprint from flask import render_template, request, jsonify from echo_telegram_base import try_except, dao from app_logger import logger from flask_login import login_required, current_user import json from datetime import timedelta dashboard_view = Blueprint("dashboard_view", __name__) @dashboard_view.route('/dashboard', methods=['POST', 'GET']) @try_except @login_required def dashboard(): # 현재 사용자의 이벤트들을 select 해서 가져온 다음 넘겨줌 cursor = dao.get_conn().cursor() cursor.execute(''' select users.user_id ,rank, status, name, seat_location, users.id, category, place, subject, start_time, attendants, channel_name, iscomplete from users left join channels on users.channel_id = channels.id left join events on users.id = events.user_id and iscomplete = 0 where users.channel_id = %s; ''', [current_user.channel]) events = [dict((cursor.description[idx][0], value) for idx, value in enumerate(row)) for row in cursor.fetchall()] for event in events: if event['attendants'] is not None: attendants_text = event['attendants'].replace('\r\n', '||') event['attendants'] = attendants_text # if request.get == reload 면 json으로 response 보내기 if request.method == 'POST': # events 돌면서 time 들어가는 속성들 문자열로 바꿔주기 for event in events: for key, value in event.items(): if type(value) is timedelta: event[key] = unicode(str(value), 'utf-8') return jsonify(result=events) return render_template('dashboard.html', events=events)
{"/echo_telegram_base.py": ["/echo_telegram_conf.py", "/db/user.py", "/api/login.py", "/views/main.py", "/views/dashboard.py", "/api/signup.py", "/api/register_channel.py", "/api/user.py", "/api/echo.py"], "/api/register_channel.py": ["/echo_telegram_base.py"], "/views/dashboard.py": ["/echo_telegram_base.py"], "/api/user.py": ["/echo_telegram_base.py"], "/api/signup.py": ["/echo_telegram_base.py"], "/api/login.py": ["/echo_telegram_base.py", "/api/signup.py", "/db/user.py"]}
70,068
G-C62/echo_telegram
refs/heads/master
/api/user.py
# -*- coding:utf-8 -*- from flask.blueprints import Blueprint from flask.globals import request, g from flask.helpers import flash, url_for from flask import redirect, jsonify from flask_login import current_user, login_required from echo_telegram_base import try_except, dao from app_logger import logger user_api = Blueprint("user_api", __name__) @user_api.route('/update/location') @login_required def update_location(): user_location = request.args.get("location").encode("utf-8") # db에 가서 user정보 변경 if user_location: cursor = dao.get_conn().cursor() cursor.execute('''update users set seat_location = %s where user_id = %s;''', [user_location, current_user.userId]) cursor.close() g.conn.commit() return redirect(url_for('dashboard_view.dashboard')) @user_api.route('/update/return') @login_required def return_seat(): # status 수정 cursor = dao.get_conn().cursor() cursor.execute('''update users set status = 'place' where user_id = %s;''', [current_user.userId]) #events의 iscompolete 수정 cursor.execute('''update events set iscomplete = 1 where user_id = (select id from users where user_id = %s) and iscomplete = 0;''', [current_user.userId]) cursor.close() g.conn.commit() return redirect(url_for('dashboard_view.dashboard'))
{"/echo_telegram_base.py": ["/echo_telegram_conf.py", "/db/user.py", "/api/login.py", "/views/main.py", "/views/dashboard.py", "/api/signup.py", "/api/register_channel.py", "/api/user.py", "/api/echo.py"], "/api/register_channel.py": ["/echo_telegram_base.py"], "/views/dashboard.py": ["/echo_telegram_base.py"], "/api/user.py": ["/echo_telegram_base.py"], "/api/signup.py": ["/echo_telegram_base.py"], "/api/login.py": ["/echo_telegram_base.py", "/api/signup.py", "/db/user.py"]}
70,069
G-C62/echo_telegram
refs/heads/master
/api/signup.py
# -*- coding:utf-8 -*- from flask.blueprints import Blueprint from flask.globals import request, g from flask.helpers import flash, url_for from flask import redirect, jsonify, flash from werkzeug.security import generate_password_hash from echo_telegram_base import try_except, dao from app_logger import logger signup_api = Blueprint("signup_api", __name__) rank_list = ['실장', '팀장', '부장', '차장', '과장', '대리' ,'사원'] # user_id에 해당하는 계정이 있는지 확인하는 method @try_except def __get_user(user_id): logger.info('search_user_by id : '+user_id) query = '''select id, user_id, name, rank from users where user_id = %s''' cursor = dao.get_conn().cursor() cursor.execute(query, [user_id]) current_user = cursor.fetchone() cursor.close() g.conn.commit() return current_user @try_except @signup_api.route("/sign_up", methods=['POST']) def sign_up(): id = request.values.get("signup_id").encode("utf-8") if "signup_id" in request.values else '' pw = request.values.get("signup_pw") if "signup_pw" in request.values else '' pw_check = request.values.get("signup_pw_check") if "signup_pw_check" in request.values else '' name = request.values.get("signup_name").encode("utf-8") if "signup_name" in request.values else '' rank = request.values.get("signup_rank").encode("utf-8") if "signup_rank" in request.values else '' if rank not in rank_list: flash('그런 직급은 없습니다 돌아가세요') return redirect(url_for('main_view.index')) logger.info('register_action data : ' + id + ', ' + name + ', ' + rank) hashed_pw = generate_password_hash(pw, salt_length=10) cursor = dao.get_conn().cursor() cursor.execute('''insert into users(user_id, pw, name, rank) values(%s, %s, %s, %s)''', [id, hashed_pw, name, rank]) cursor.close() g.conn.commit() flash('회원가입 성공') return redirect(url_for('main_view.index')) # id중복검사 @try_except @signup_api.route("/sign_up/check_id", methods=['POST']) def check_id(): user_id = request.json['user_id'] if __get_user(user_id): return jsonify(result=False) else: return jsonify(result=True)
{"/echo_telegram_base.py": ["/echo_telegram_conf.py", "/db/user.py", "/api/login.py", "/views/main.py", "/views/dashboard.py", "/api/signup.py", "/api/register_channel.py", "/api/user.py", "/api/echo.py"], "/api/register_channel.py": ["/echo_telegram_base.py"], "/views/dashboard.py": ["/echo_telegram_base.py"], "/api/user.py": ["/echo_telegram_base.py"], "/api/signup.py": ["/echo_telegram_base.py"], "/api/login.py": ["/echo_telegram_base.py", "/api/signup.py", "/db/user.py"]}
70,070
G-C62/echo_telegram
refs/heads/master
/api/login.py
# -*- coding:utf-8 -*- from flask.blueprints import Blueprint from flask import url_for, redirect, flash from werkzeug.security import check_password_hash from flask.globals import request, g from echo_telegram_base import try_except, dao, app from app_logger import logger from api.signup import __get_user from db.user import User from flask import session from flask_login.utils import login_user, login_required, logout_user login_api = Blueprint("login_api", __name__) @try_except def check_pw(login_id, pw): query = '''select pw from users where id = %s''' cursor = dao.get_conn().cursor() cursor.execute(query, [login_id]) db_pw = cursor.fetchone() cursor.close() g.conn.commit() return check_password_hash(db_pw[0], pw) @login_api.route('/login', methods=['POST']) def login(): login_userId = request.form['login_id'].encode("utf-8") login_pw = request.form['login_pw'].encode("utf-8") user = __get_user(login_userId) if user: if check_pw(user[0], login_pw): user = User(userId=user[1].decode('utf-8'), name=user[2].decode('utf-8'), rank=user[3], status='place'\ , channel=None, location=None, auth=False) login_user(user) session['userId'] = login_userId return redirect(url_for('dashboard_view.dashboard')) #로그인에 실패함 flash(u'입력정보를 다시 확인해주세요'); return redirect(url_for('main_view.index')) @login_api.route('/logout') @login_required def logout(): logout_user() return redirect(url_for('main_view.index'))
{"/echo_telegram_base.py": ["/echo_telegram_conf.py", "/db/user.py", "/api/login.py", "/views/main.py", "/views/dashboard.py", "/api/signup.py", "/api/register_channel.py", "/api/user.py", "/api/echo.py"], "/api/register_channel.py": ["/echo_telegram_base.py"], "/views/dashboard.py": ["/echo_telegram_base.py"], "/api/user.py": ["/echo_telegram_base.py"], "/api/signup.py": ["/echo_telegram_base.py"], "/api/login.py": ["/echo_telegram_base.py", "/api/signup.py", "/db/user.py"]}
70,073
dalerxli/pyfab
refs/heads/master
/pyfablib/traps/__init__.py
from QTrap import QTrap from QTrapGroup import QTrapGroup from QTrappingPattern import QTrappingPattern from QTrapWidget import QTrapWidget __all__ = ['QTrap', 'QTrapGroup', 'QTrappingPattern', 'QTrapWidget']
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,074
dalerxli/pyfab
refs/heads/master
/tasks/rendertextas.py
from rendertext import rendertext from PyQt4.QtGui import QInputDialog class rendertextas(rendertext): def __init__(self, **kwargs): super(rendertextas, self).__init__(**kwargs) qtext, ok = QInputDialog.getText(self.parent, 'Render Text', 'Text:') if ok: self.text = str(qtext) else: self.text = 'hello'
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,075
dalerxli/pyfab
refs/heads/master
/common/SerialDevice.py
import serial from serial.tools.list_ports import comports import io import fcntl import logging class SerialDevice(object): def __init__(self, eol='\r', manufacturer='Prolific', baudrate=9600, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=0.1): self.eol = eol self.manufacturer = manufacturer self.baudrate = baudrate self.bytesize = bytesize self.parity = parity self.stopbits = stopbits self.timeout = timeout if not self.find(): raise ValueError('Could not find serial device') def find(self): ports = list(comports()) if len(ports) <= 0: logging.warning('No serial ports identified') return for port in ports: if port.manufacturer is None: continue if self.manufacturer not in port.manufacturer: continue try: self.ser = serial.Serial(port.device, baudrate=self.baudrate, bytesize=self.bytesize, parity=self.parity, stopbits=self.stopbits, timeout=self.timeout) if self.ser.isOpen(): try: fcntl.flock(self.ser.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError: logging.warning('%s is busy', self.ser.port) self.ser.close() continue else: logging.warning('Could not open %s', self.ser.port) continue except serial.SerialException as ex: logging.warning('%s is unavailable: %s', port, ex) continue buffer = io.BufferedRWPair(self.ser, self.ser, 1) # buffer = io.BufferedRandom(self.ser, 1) self.sio = io.TextIOWrapper(buffer, newline=self.eol, line_buffering=True) if self.identify(): return True self.ser.close() return False def identify(self): return False def close(self): self.ser.close() def write(self, str): self.sio.write(unicode(str + self.eol)) def readln(self): return self.sio.readline().decode().strip() def available(self): return self.ser.in_waiting
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,076
dalerxli/pyfab
refs/heads/master
/jansenlib/video/QCameraDevice.py
#!/usr/bin/env python """QCameraDevice.py: pyqtgraph module for OpenCV video camera.""" import cv2 from pyqtgraph.Qt import QtCore def is_cv2(): return cv2.__version__.startswith("2.") class QCameraThread(QtCore.QThread): """Grab frames as fast as possible in a separate thread to minimize latency for frame acquisition. """ def __init__(self, camera): super(QCameraThread, self).__init__() self.camera = camera self.keepGrabbing = True def __del__(self): self.wait() def run(self): while self.keepGrabbing: self.camera.grab() def stop(self): self.keepGrabbing = False class QCameraDevice(QtCore.QObject): """Low latency OpenCV camera intended to act as an image source for PyQt applications. """ _DEFAULT_FPS = 29.97 def __init__(self, cameraId=0, size=None, parent=None): super(QCameraDevice, self).__init__(parent) self.camera = cv2.VideoCapture(cameraId) self.thread = QCameraThread(self.camera) self.size = size #try: # if is_cv2(): # self.fps = int(self.camera.get(cv2.cv.CV_CAP_PROP_FPS)) # else: # self.fps = int(self.camera.get(cv2.CAP_PROP_FPS)) #except: # print('got error') self.fps = self._DEFAULT_FPS # Reduce latency by continuously grabbing frames in a background thread def start(self): self.thread.start() return self def stop(self): self.thread.stop() def close(self): self.stop() self.camera.release() # Read requests return the most recently grabbed frame def read(self): if self.thread.isRunning(): ready, frame = self.camera.retrieve() else: ready, frame = False, None return ready, frame @property def size(self): if is_cv2(): h = int(self.camera.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT)) w = int(self.camera.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH)) else: h = int(self.camera.get(cv2.CAP_PROP_FRAME_HEIGHT)) w = int(self.camera.get(cv2.CAP_PROP_FRAME_WIDTH)) return QtCore.QSize(w, h) @size.setter def size(self, size): if size is None: return if is_cv2(): self.camera.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, size[1]) self.camera.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, size[0]) else: self.camera.set(cv2.CAP_PROP_FRAME_HEIGHT, size[1]) self.camera.set(cv2.CAP_PROP_FRAME_WIDTH, size[0]) @property def fps(self): return self._fps @fps.setter def fps(self, fps): if (fps > 0): self._fps = float(fps) else: self._fps = self._DEFAULT_FPS @property def roi(self): return QtCore.QRectF(0., 0., self.size.width(), self.size.height())
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,077
dalerxli/pyfab
refs/heads/master
/tasks/cleartraps.py
from task import task class cleartraps(task): def __init__(self, **kwargs): super(cleartraps, self).__init__(**kwargs) def dotask(self): self.parent.pattern.clearTraps()
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,078
dalerxli/pyfab
refs/heads/master
/jansenlib/video/QFabFilter.py
from PyQt4 import QtGui, QtCore from vmedian import vmedian import numpy as np import cv2 from matplotlib.pylab import cm class QFabFilter(QtGui.QFrame): def __init__(self, video): super(QFabFilter, self).__init__() self.video = video self.init_filters() self.init_ui() def init_filters(self): shape = self.video.shape() self.median = vmedian(order=3, shape=shape) def init_ui(self): self.setFrameShape(QtGui.QFrame.Box) layout = QtGui.QVBoxLayout(self) layout.setMargin(1) title = QtGui.QLabel('Video Filters') bmedian = QtGui.QCheckBox(QtCore.QString('Median')) bnormalize = QtGui.QCheckBox(QtCore.QString('Normalize')) bsample = QtGui.QCheckBox(QtCore.QString('Sample and Hold')) bndvi = QtGui.QCheckBox(QtCore.QString('NDVI')) layout.addWidget(title) layout.addWidget(bmedian) layout.addWidget(bnormalize) layout.addWidget(bsample) layout.addWidget(bndvi) bmedian.clicked.connect(self.handleMedian) bnormalize.clicked.connect(self.handleNormalize) bsample.clicked.connect(self.handleSample) bndvi.clicked.connect(self.handleNDVI) @QtCore.pyqtSlot(bool) def handleMedian(self, selected): if selected: self.video.registerFilter(self.median.filter) else: self.video.unregisterFilter(self.median.filter) def normalize(self, frame): self.median.add(frame) med = self.median.get() med = np.clip(med, 1, 255) nrm = frame.astype(float) / med return np.clip(100 * nrm, 0, 255).astype(np.uint8) @QtCore.pyqtSlot(bool) def handleNormalize(self, selected): if selected: self.video.registerFilter(self.normalize) else: self.video.unregisterFilter(self.normalize) def samplehold(self, frame): if not frame.shape == self.median.shape: self.median.add(frame) if not self.median.initialized: self.median.add(frame) self.background = np.clip(self.median.get(), 1, 255) nrm = frame.astype(float) / self.background return np.clip(100 * nrm, 0, 255).astype(np.uint8) @QtCore.pyqtSlot(bool) def handleSample(self, selected): if selected: self.median.reset() self.video.registerFilter(self.samplehold) else: self.video.unregisterFilter(self.samplehold) def ndvi(self, frame): if frame.ndim == 3: (r, g, b) = cv2.split(frame) r = r.astype(float) g = g.astype(float) ndx = (r - g) / np.clip(r + g, 1., 255) ndx = np.clip(128. * ndx + 127., 0, 255).astype(np.uint8) else: ndx = frame ndx = cm.RdYlGn_r(ndx, bytes=True) ndx = cv2.cvtColor(ndx, cv2.COLOR_BGRA2BGR) return ndx @QtCore.pyqtSlot(bool) def handleNDVI(self, selected): if selected: self.video.registerFilter(self.ndvi) else: self.video.unregisterFilter(self.ndvi)
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,079
dalerxli/pyfab
refs/heads/master
/pyfablib/proscan/QProscan.py
from PyQt4 import QtGui, QtCore from .pyproscan import pyproscan import atexit class QProscan(QtGui.QFrame): def __init__(self): super(QProscan, self).__init__() self.instrument = pyproscan() self.initUI() atexit.register(self.shutdown) self._timer = QtCore.QTimer(self) self._timer.timeout.connect(self.update) self._timer.setInterval(200) self._timer.start() def stop(self): self._timer.stop() def start(self): self._timer.start() return self def shutdown(self): self.stop() self.instrument.close() def initUI(self): self.setFrameShape(QtGui.QFrame.Box) self.wx = self.counter_widget() self.wy = self.counter_widget() self.wz = self.counter_widget() self.bstop = QtGui.QPushButton('Stop') self.bstop.clicked.connect(self.instrument.stop) layout = QtGui.QGridLayout() layout.setMargin(1) layout.setHorizontalSpacing(1) layout.setVerticalSpacing(1) layout.addWidget(QtGui.QLabel('Stage'), 1, 1, 1, 4) layout.addWidget(QtGui.QLabel('x'), 2, 1) layout.addWidget(QtGui.QLabel('y'), 2, 2) layout.addWidget(QtGui.QLabel('z'), 2, 3) layout.addWidget(self.wx, 3, 1) layout.addWidget(self.wy, 3, 2) layout.addWidget(self.wz, 3, 3) layout.addWidget(self.bstop, 3, 4) self.setLayout(layout) def counter_widget(self): lcd = QtGui.QLCDNumber(self) lcd.setNumDigits(9) lcd.setSegmentStyle(QtGui.QLCDNumber.Flat) palette = lcd.palette() palette.setColor(palette.WindowText, QtGui.QColor(0, 0, 0)) palette.setColor(palette.Background, QtGui.QColor(255, 255, 224)) lcd.setPalette(palette) lcd.setAutoFillBackground(True) return lcd def update(self): position = self.instrument.position() if position is not None: self.wx.display(position[0]) self.wy.display(position[1]) self.wz.display(-position[2]) # NOTE: Special sign def setXOrigin(self): self.instrument.setPosition(x=0) def setYOrigin(self): self.instrument.setPosition(y=0) def setZOrigin(self): self.instrument.setPosition(z=0) def main(): import sys app = QtGui.QApplication(sys.argv) stage = QProscan() stage.show() sys.exit(app.exec_()) if __name__ == '__main__': main()
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,080
dalerxli/pyfab
refs/heads/master
/tasks/calibrate_cgh.py
from maxtask import maxtask from PyQt4.QtGui import QVector3D class calibrate_cgh(maxtask): def __init__(self, **kwargs): super(calibrate_cgh, self).__init__(**kwargs) def setParent(self, parent): self.parent = parent self.parent.pattern.clearTraps() rc = self.parent.cgh.rc r1 = rc + QVector3D(100, 0, 0) r2 = rc - QVector3D(0, 100, 0) r = [r1, r2] self.parent.pattern.createTraps(r)
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,081
dalerxli/pyfab
refs/heads/master
/jansen.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Jansen is a video-capture GUI intended for holographic video microscopy""" from PyQt4 import QtGui from jansenlib.QJansenWidget import QJansenWidget import sys class jansen(QtGui.QMainWindow): def __init__(self): super(jansen, self).__init__() self.instrument = QJansenWidget() self.init_ui() self.show() tabs = self.instrument.tabs tabs.setFixedWidth(tabs.width()) def init_ui(self): self.setWindowTitle('Jansen') self.statusBar().showMessage('Ready') menubar = self.menuBar() fileMenu = menubar.addMenu('&File') exitIcon = QtGui.QIcon.fromTheme('exit') exitAction = QtGui.QAction(exitIcon, '&Exit', self) exitAction.setShortcut('Ctrl-Q') exitAction.setStatusTip('Exit PyFab') exitAction.triggered.connect(QtGui.qApp.quit) fileMenu.addAction(exitAction) self.setCentralWidget(self.instrument) if __name__ == '__main__': app = QtGui.QApplication(sys.argv) instrument = jansen() sys.exit(app.exec_())
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,082
dalerxli/pyfab
refs/heads/master
/tasks/maxtask.py
from task import task import numpy as np import cv2 class maxtask(task): def __init__(self, nframes=10, **kwargs): super(maxtask, self).__init__(nframes=nframes, **kwargs) self.frame = None def doprocess(self, frame): if self.frame is None: self.frame = frame else: self.frame = np.maximum(frame, self.frame) def dotask(self): fn = self.parent.config.filename(prefix='maxtask', suffix='.png') cv2.imwrite(fn, self.frame)
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}
70,083
dalerxli/pyfab
refs/heads/master
/jansenlib/DVR/fabdvr.py
#!/usr/bin/env python import cv2 import os class fabdvr(object): def __init__(self, source=None, filename='~/data/fabdvr.avi', codec='HFYU', **kwds): """Record digital video stream with lossless compression :param camera: object reference to QCameraItem :param filename: video file name. Extension determines container. ; Not all containers work with all codecs. :param codec: FOURCC descriptor for video codec :returns: :rtype: ; ;Note on codecs: ; On macs, FFV1 appears to work with avi containers ; On Ubuntu 16.04, HFYU works with avi container. ; FFV1 fails silently ; LAGS does not work (not found) """ super(fabdvr, self).__init__(**kwds) self._writer = None self.source = source self.filename = filename self._framenumber = 0 self._nframes = 0 if cv2.__version__.startswith('2'): self._fourcc = cv2.cv.CV_FOURCC(*codec) else: self._fourcc = cv2.VideoWriter_fourcc(*codec) def record(self, nframes=100): if self.isrecording(): return if (nframes > 0): self._nframes = nframes self.start() def start(self): if self.source is None: return self.framenumber = 0 self._writer = cv2.VideoWriter(self.filename, self._fourcc, self.source.device.fps, self.size(), not self.source.gray) self.source.sigNewFrame.connect(self.write) def stop(self): if self.isrecording(): self.source.sigNewFrame.disconnect(self.write) self._writer.release() self.nframes = 0 self._writer = None def write(self, frame): if self.source.transposed: frame = cv2.transpose(frame) if self.source.flipped: frame = cv2.flip(frame, 0) self._writer.write(frame) self.framenumber += 1 if (self.framenumber == self._nframes): self.stop() @property def filename(self): return self._filename @filename.setter def filename(self, filename): if not self.isrecording(): self._filename = os.path.expanduser(filename) def isrecording(self): return (self._writer is not None) def size(self): if self.source is None: return None else: sz = self.source.device.size w = int(sz.width()) h = int(sz.height()) return (w, h) def framenumber(self): return self._framenumber if __name__ == '__main__': from PyQt4 import QtGui from QCameraDevice import QCameraDevice from QVideoItem import QVideoWidget import sys app = QtGui.QApplication(sys.argv) device = QCameraDevice(size=(640, 480), gray=True) source = QVideoItem(device) widget = QVideoWidget(source, background='w') widget.show() dvr = fabdvr(source=source) dvr.record(24) sys.exit(app.exec_())
{"/pyfablib/proscan/QProscan.py": ["/pyfablib/proscan/pyproscan.py"], "/jansen.py": ["/jansenlib/QJansenWidget.py"], "/pyfablib/proscan/pyproscan.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/ipglaser.py": ["/common/SerialDevice.py"], "/pyfablib/IPG/QIPGLaser.py": ["/pyfablib/IPG/ipglaser.py"], "/pyfablib/CGH/QCGH.py": ["/common/QPropertySheet.py"], "/jansenlib/QJansenWidget.py": ["/tasks/taskmanager.py"], "/pyfab.py": ["/pyfablib/QFabWidget.py", "/common/fabconfig.py"], "/jansenlib/DVR/QFabDVR.py": ["/jansenlib/DVR/fabdvr.py", "/common/clickable.py"], "/jansenlib/video/QFabVideo.py": ["/common/QPropertySheet.py"], "/pyfablib/QFabWidget.py": ["/jansenlib/QJansenWidget.py"]}