index
int64
repo_name
string
branch_name
string
path
string
content
string
import_graph
string
45,095
valisfree/rainreader_v1
refs/heads/master
/func.py
# -*- coding: utf-8 -*- #----------------------------------------------------------------------- # Name: Rain.reader # Created: 09.11.2018 # Version: 0.1 # Copyright: (c) 2018, Vale_Phtor, valisfree@yandex.ru phtor.ru # Licence: Apache License version 2.0 #----------------------------------------------------------------------- import sqlite3 import time import os from datetime import datetime import codecs ############ OPEN FILE ########## def open_and_read_book_file(file_name): ''' Открывает и считывает данные из файла(книги). Возвращает список слов. ''' words_list = [] if file_name == '': return else: with codecs.open(file_name, "r",encoding='utf-8', errors='ignore') as inf: for line in inf: line = line.strip() line = line.split() for str in line: words_list.append(str) return words_list def checkFileSize(file_name): return os.path.getsize(file_name) def adressToNamefile(adress): adr = '' adress = adress[::-1] for i in adress: adr += i if i == '/' or i =='\\': adr = adr[::-1] return adr[1:] def sizeFile(adress): return os.stat(adress).st_size ############# SQLite ############ def createDataBase(): check_db = not os.path.exists('rain.db') if check_db: conn = sqlite3.connect("rain.db") cursor = conn.cursor() cursor.execute("""CREATE TABLE books (adress text PRIMARY KEY, name text, cur number, speed number, data1 number, size number) """) conn.close() def addToDataBase(adress, cur, speed): size = checkFileSize(adress) name = adressToNamefile(adress) ''' data1 = datetime.utcfromtimestamp(timestamp) ''' data1 = int(time.mktime(time.gmtime())) size = sizeFile(adress) conn = sqlite3.connect("rain.db") cursor = conn.cursor() cursor.execute("INSERT OR IGNORE INTO books VALUES (?, ?, ?, ?, ?, ?)", (adress, name, cur, speed, data1, size) ) conn.commit() conn.close() def loadCurAndSpeedFromDataBase(adress): conn = sqlite3.connect("rain.db") cursor = conn.cursor() for row in cursor.execute("SELECT rowid, * FROM books ORDER BY adress"): if row[1] == adress: cur_speed = (row[3],row[4]) conn.close() return cur_speed conn.close() def updateDataBase(adress, cur, speed): size = checkFileSize(adress) name = adressToNamefile(adress) data1 = int(time.mktime(time.gmtime())) size = sizeFile(adress) conn = sqlite3.connect("rain.db") cursor = conn.cursor() cursor.execute("INSERT OR REPLACE INTO books VALUES (?, ?, ?, ?, ?, ?)", (adress, name, cur, speed, data1, size) ) conn.commit() conn.close() # for debug, print all table def printDataBase(): conn = sqlite3.connect("rain.db") cursor = conn.cursor() for row in cursor.execute("SELECT rowid, * FROM books ORDER BY adress"): print(row) conn.close() # printDataBase() ############# GET WORD ########## def get_word(words_list, cur): if cur >= len(words_list): return False return words_list[cur] ############# TIME ############ time_for_punctuation = 0.12 time_for_long_words = 0.08 # if len word > 5 def speed(speed): """ Принимает скорость. Возвращает базовое время вывода одного слова. """ x = 60 / speed y = x * 5 # препдолагаю, что 3 слова обычных, одно больше 5 букв и один знак пунктуации z = (3 * x) + (x + time_for_punctuation) + (x + time_for_long_words) a = (z - y) / 5 # разница от среднего значения. Поправка на 2 из 5 слов base_time = x - a return base_time def stream_time_pause(word, base_time): ''' Создает задержку между выводом следующего слова. ''' delta = word_time_lench(word) + time_punktuation(word) counting_time = base_time + delta return counting_time * 1000 def word_time_lench(word): """ Считает длину слова. Возвращает значение прибавки к задержке """ counted_time = 0 if len(word) > 5: counted_time += time_for_long_words return counted_time def time_punktuation(word): """ Ищет знаки препинания. Возвращает значение прибавки к задержке. """ counted_time = 0 if ',' or '.' or '!' in word: counted_time += time_for_punctuation return counted_time ############ END TIME ###########
{"/main.py": ["/func.py"]}
45,096
valisfree/rainreader_v1
refs/heads/master
/main.py
# -*- coding: utf-8 -*- #------------------------------------------------------------------------------- # Name: Rain.reader # Created: 09.11.2018 # Version: 0.1 # Copyright: (c) 2018, Vale_Phtor, valisfree@yandex.ru phtor.ru # Licence: Apache License version 2.0 #------------------------------------------------------------------------------- import os from tkinter import * from tkinter import filedialog as fd import func # глобальные переменные words_list = [] # список слов книги cur = 0 # позиция в списке слов книги speed = 0 # скорость чтения слов в минуту flag = 0 # флаг включения режима чтения adress = '' func.createDataBase() def openBook(): global words_list global adress global cur adress = fd.askopenfilename(filetypes = (("txt files","*.txt"),("all files","*.*"))) if adress == tuple(): check_word_list() return else: words_list = func.open_and_read_book_file(adress) if not check_word_list(): func.addToDataBase(adress, cur, speed) cur_and_speed = func.loadCurAndSpeedFromDataBase(adress) if cur_and_speed[1] == 0: return s1.set(cur_and_speed[1]) # меняет значение шкалы. cur = cur_and_speed[0] - 1 l1.configure(text=words_list[cur]) def check_word_list(): if len(words_list) == 0: word = 'no file open' f_top.configure(text=word) return False word = 'file open' f_top.configure(text=word) ########## STREAM def flag_start_stop(event): global flag if flag == 0: flag = 1 update_label() return if flag == 1: flag = 0 return def update_label(event=0): if check_word_list() == False: return global cur if flag == 1: word = func.get_word(words_list, cur) if word == False: l1.configure(text="End book") return l1.configure(text=word) cur += 1 time = int(func.stream_time_pause(word, func.speed(speed))) root.after(time, update_label) def scaleInput(i): global speed speed = int(i) def savePos(): if cvar1.get() == True: func.updateDataBase(adress, cur, speed) def about(): a = Toplevel() a.geometry('300x75') a.title("Rain reader") a['bg'] = 'gray' a.resizable(False, False) f_top = LabelFrame(a, bg='gray', text='About') t1 = 'Rain reader - program for speed reading.' t2 = 'Words like rain will fall on your head.' t3 = 'Open .txt files.' l1 = Label(f_top,text=t1, bg='gray') l2 = Label(f_top,text=t2, bg='gray') l3 = Label(f_top,text=t3, bg='gray') f_top.pack() l1.pack(fill=X) l2.pack(fill=X) l3.pack(fill=X) root = Tk() mainmenu = Menu(root) root.geometry("450x300+300+300") root.minsize(350,250) if 'nt' == os.name: root.iconbitmap("fav.ico") else: root.iconbitmap("@fav.xbm") root.title("Rain reader") root.config(menu=mainmenu) mainmenu.add_command(label='File', command=openBook) # mainmenu.add_command(label='Options') mainmenu.add_command(label='About', command=about) f_top = LabelFrame(root, text='Stream') l1 = Label(f_top, width=150, height=5, text="stream", bg='gray', font="Arial 16") l1['text'] = 'Click for start/pause' l1.bind('<Button-1>', flag_start_stop) root.bind('<space>', flag_start_stop) ''' l1.bind('<FocusIn>', testirovka) l1.bind('<FocusOut>', testirovka) ''' s1 = Scale(f_top, from_=300, to=1000, resolution=5, tickinterval=200, troughcolor='grey', orient=HORIZONTAL, command=scaleInput) s1.set(320) cvar1 = BooleanVar() cvar1.set(0) c1 = Checkbutton(root, text="Save", variable=cvar1, onvalue=1, offvalue=0, command=savePos) f_top.pack(fill=X, padx=5, pady=5) l1.pack(fill=X) s1.pack(fill=X, padx=5, pady=5) c1.pack(anchor=NE, padx=5, pady=5) root.mainloop()
{"/main.py": ["/func.py"]}
45,098
CHALASS770/WOG
refs/heads/master
/e2e.py
from selenium import webdriver from selenium.common.exceptions import WebDriverException from time import sleep from selenium.webdriver.chrome.options import Options print("test") def test_score_webservice(): print(1) Url = "http://127.0.0.1:8777" print(3) chrome_options = Options() chrome_options.add_argument("--headless") chrome_options.add_argument('--no-sandbox') driver = webdriver.Chrome(executable_path='C:\chromedriver.exe', options=chrome_options) print(2) driver.get(Url) sleep(3) res = driver.find_element_by_id("score") test = int(res.text) print(4) if test >= 1 and test <= 1000: print("True") return True else: print("False") return False def main_test() : test = test_score_webservice() print(0) main_test()
{"/MainGame.py": ["/live.py", "/Scores.py"], "/Scores.py": ["/Utils.py"], "/live.py": ["/GuessGame.py", "/MemoryGame.py", "/CurrencyRouletteGame.py"]}
45,099
CHALASS770/WOG
refs/heads/master
/GuessGame.py
from random import * class GuessGame : def __init__(self): self.secretNumber = 1 self.difficulty= -1 self.chance=5 def generat_number(self, difficulty): self.secretNumber = int(randint(0, difficulty*10)) self.chance=self.chance+1-difficulty def get_secret_number(self): return self.secretNumber def guess_from_user(self): valideplay = True while valideplay == True: try: self.difficulty = int(input("enter a number")) valideplay = False except: print('please enter a numeric value') def guet_guess_from_user(self): return self.difficulty def compare_result(self): print('Good luck') while self.chance > 0 and self.get_secret_number() != self.guet_guess_from_user(): print('you have ', self.chance, ' chance') self.guess_from_user() self.chance = self.chance - 1 if self.get_secret_number()== self.guet_guess_from_user(): print("you Win") elif self.chance == 0: print("you lost") print('the value was ', self.secretNumber)
{"/MainGame.py": ["/live.py", "/Scores.py"], "/Scores.py": ["/Utils.py"], "/live.py": ["/GuessGame.py", "/MemoryGame.py", "/CurrencyRouletteGame.py"]}
45,100
CHALASS770/WOG
refs/heads/master
/MainGame.py
from live import * from Scores import * from MainScore import * name = input("whats your name ?") welcome(name) while True: play, level = load_game() play_game(play,level) Score = Scores(name, play ,level) Score.Write_Score() want=input('do you want play again ? y/n') if want == 'n' : break
{"/MainGame.py": ["/live.py", "/Scores.py"], "/Scores.py": ["/Utils.py"], "/live.py": ["/GuessGame.py", "/MemoryGame.py", "/CurrencyRouletteGame.py"]}
45,101
CHALASS770/WOG
refs/heads/master
/Utils.py
class Utils : def __init__(self, namePlayer, play ,myscore): self.score_file_name = "" self.bad_return_code = -1 self.chance=5 self.score=myscore self.nameplay = namePlayer if play == 1: self.play = "Memorygame" elif play == 2: self.play = "GuessGame" elif play == 3: self.play = "Roulette Game" '''def Screen_Cleaner():''' def write_score(self): self.score_file_name = open("score.txt", "w") self.score_file_name.write(self.score) self.score_file_name.close() def read_score(self): self.score_file_name = open("score.txt", "r") print(self.score_file_name.read()) self.score_file_name.close()
{"/MainGame.py": ["/live.py", "/Scores.py"], "/Scores.py": ["/Utils.py"], "/live.py": ["/GuessGame.py", "/MemoryGame.py", "/CurrencyRouletteGame.py"]}
45,102
CHALASS770/WOG
refs/heads/master
/Scores.py
from Utils import * class Scores : def __init__(self ,nameP, play, difficult) : self.score = 0 self.diffic = difficult self.namep = nameP self.Play = play self.newscore = 0 def Write_Score(self): self.score = self.diffic * 3 + 5 self.score = str(self.score) self.newscore = Utils(self.namep, self.Play, self.score) self.newscore.write_score() def read(self): self.newscore.read_score()
{"/MainGame.py": ["/live.py", "/Scores.py"], "/Scores.py": ["/Utils.py"], "/live.py": ["/GuessGame.py", "/MemoryGame.py", "/CurrencyRouletteGame.py"]}
45,103
CHALASS770/WOG
refs/heads/master
/MemoryGame.py
from random import * from time import sleep class MemoryGame : def __init__(self, difficult): self.my_sequence = [] self.list_from_user = [] self.difficulty = difficult*2 #self.valid=0 def generate_sequence(self): for lenght in range(self.difficulty): self.my_sequence.append(int(randint(0, 101))) print('the sequence is : ', self.my_sequence) sleep(0.7) for i in range(30): print('') def get_list_from_user(self): for lenght in range(self.difficulty): self.list_from_user.append(int(input('enter the value '))) def is_list_equal(self): valid=0 for lenght in self.my_sequence: for list_user in self.list_from_user: if lenght == list_user: valid = valid + 1 if valid == self.difficulty: return True else: return False def play(self): self.generate_sequence() self.get_list_from_user() if self.is_list_equal()==True : print('you win') else: print('you lost')
{"/MainGame.py": ["/live.py", "/Scores.py"], "/Scores.py": ["/Utils.py"], "/live.py": ["/GuessGame.py", "/MemoryGame.py", "/CurrencyRouletteGame.py"]}
45,104
CHALASS770/WOG
refs/heads/master
/CurrencyRouletteGame.py
from random import * from time import sleep class CurrencyRouletteGame: def __init__(self, difficult): self.total_money = int(randint(5,1000)) self.intermin = 0 self.intermax = 0 self.difficult = difficult self.useramount = 0 def get_money_interval(self): self.intermin=self.total_money - (5 - self.difficult) self.intermax=self.total_money + (5 - self.difficult) def get_guess_from_user(self): print(self.total_money,' USD') self.useramount=int(input('enter a value in ILS')) def play(self): self.get_money_interval() self.get_guess_from_user() if self.intermin<self.useramount<self.intermax: print('you win') else: print('you lost') print(self.intermin,'< ',self.useramount,'< ',self.intermax)
{"/MainGame.py": ["/live.py", "/Scores.py"], "/Scores.py": ["/Utils.py"], "/live.py": ["/GuessGame.py", "/MemoryGame.py", "/CurrencyRouletteGame.py"]}
45,105
CHALASS770/WOG
refs/heads/master
/live.py
from GuessGame import * from time import sleep from MemoryGame import * from CurrencyRouletteGame import * def welcome(name): print("Hello %s ! Welcome in World of Game!!! "% name) print("Here you can find many cool games to play ") def load_game(): valideplay = True while valideplay == True: try : play=int(input("Please choose a game to play: \n 1. Memory Game - a sequence of numbers will appear for 1 second and you have to guess it back \n 2. Guess Game - guess a number and see if you chose like the computer \n 3. Weather Roulette - Guess the current temperature currently in Jerusalem \n")) if 1 <= play <= 3 : valideplay = False else: raise ValueError("your choice is invalide") except ValueError: print("****please enter a valid value ****** \n ********************* \n") validedif = True while validedif == True: try : difficult = int(input("choose a dificult betwin 1 and 5 \n ")) if 1 <= difficult <=5 : validedif = False else : raise ValueError("your choice is invalide") except ValueError: print("****please enter a valid value**** \n ********************\n") if play == 1 : print("you choose to play to Memory Game") elif play == 2: print("you choose to play to Guess Game") elif play == 3: print("you choose to play to Weather Roulette") if difficult == 1 : print("difficult is easy") elif difficult == 2: print("difficult is easy plus") elif difficult == 3: print("difficult is hard") elif difficult == 4: print("difficult is hard plus") elif difficult == 5: print("difficult is very Hard") return play, difficult def play_game(playGame, level): sleep(3) if playGame == 2: for i in range(20): print('') print('**************************************') print('***** WELCOME TO THE GUESS GAME ******') print('**************************************') for i in range(3): print('') game = GuessGame() game.generat_number(level) game.compare_result() elif playGame == 1: for i in range(20): print('') print('**************************************') print('***** WELCOME TO THE MEMORY GAME ******') print('**************************************') for i in range(3): print('') game = MemoryGame(level) game.play() elif playGame == 3: for i in range(20): print('') print('**************************************') print('***** WELCOME TO THE ROULETTE GAME ******') print('**************************************') for i in range(3): print('') game = CurrencyRouletteGame(level) game.play()
{"/MainGame.py": ["/live.py", "/Scores.py"], "/Scores.py": ["/Utils.py"], "/live.py": ["/GuessGame.py", "/MemoryGame.py", "/CurrencyRouletteGame.py"]}
45,106
NotAnonymous33/gameOfLife
refs/heads/master
/game.py
class Game: def next_cells(self, cells): new_cells = cells grid = [(len(cells) + 2) * [0]] + [[0] + [abs(int(cell.on)) for cell in row] + [0] for row in cells] + [ (len(cells) + 2) * [0]] grid = self.next_grid(grid) for row_num in range(len(cells)): for col_num in range(len(cells[row_num])): new_cells[row_num][col_num].on = grid[row_num + 1][col_num + 1] return new_cells def next_grid(self, grid): new_grid = [list(map(abs,i[:])) for i in grid] for row in range(1, len(grid) - 1): for col in range(1, len(grid[row]) - 1): new_grid[row][col] = int(self.alive(grid, row, col)) return new_grid def alive(self, grid, row, col): count = 0 # add from row before # add cell before and after # add from row after count += sum(grid[row - 1][col - 1:col + 2]) count += grid[row][col - 1] + grid[row][col + 1] count += sum(grid[row + 1][col - 1:col + 2]) if grid[row][col] == 1 and 2 <= count <= 3: return True if grid[row][col] == 0 and count == 3: return True return False
{"/main.py": ["/game.py"]}
45,107
NotAnonymous33/gameOfLife
refs/heads/master
/main.py
import pygame from game import Game import random game = Game() length = 20 # pixels across of each cell num_rows = 40 border = 2 grey = (30, 30, 30) white = (255, 255, 255) black = (0, 0, 0) green = (0, 255, 0) class Cell: def __init__(self, x, y, window): self.x = x self.y = y self.on = False self.window = window self.xpos = 0 self.ypos = 0 # self.on = (x+y)%2==1 def draw(self, mouse_position, x): self.xpos = (length + border) * self.x self.ypos = (length + border) * self.y color = () # if mouse_position is not None: if self.hover(mouse_position) and x: color = green else: color = [black, white][self.on] pygame.draw.rect(self.window, color, [self.xpos, self.ypos, length, length]) def hover(self, mouse_position): return self.xpos <= mouse_position[0] <= self.xpos + length and self.ypos <= mouse_position[1] <= self.ypos + length def change(self): self.on = ~self.on def __repr__(self): return f"{self.x=} {self.y=} {self.on=}" pygame.init() fps = 60 gameDisplay = pygame.display.set_mode((895, 895)) clock = pygame.time.Clock() gameOn = True gameDisplay.fill(grey) # starting loop # game loop cells = [[Cell(i, j, gameDisplay) for i in range(num_rows)] for j in range(num_rows)] start = False while gameOn: if not start: for event in pygame.event.get(): if event.type == pygame.QUIT: gameOn = False if event.type == pygame.MOUSEBUTTONDOWN: for row in cells: for cell in row: if cell.hover(pygame.mouse.get_pos()): cell.change() if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: fps = 10 start = True if event.key == pygame.K_c: for row in cells: for cell in row: cell.on = False for i in range(1, 10): if event.key == eval("pygame.K_" + str(i)): for row in cells: for cell in row: r = random.randint(1, i) cell.on = r == 1 pos = pygame.mouse.get_pos() for row in cells: for cell in row: cell.draw(pos, True) else: for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: start = False fps = 60 if event.type == pygame.QUIT: gameOn = False cells = game.next_cells(cells) for row in cells: for cell in row: cell.draw((0, 0), False) pygame.display.update() clock.tick(fps) pygame.quit()
{"/main.py": ["/game.py"]}
45,108
realzhengyiming/WeatherPlatform
refs/heads/main
/weather_cralwer/weather_cralwer/db_util.py
# read_all_city_and_city_code from databases; # 导入pymysql模块 from typing import List import pymysql from WeatherWeb.WeatherWeb.settings import DATABASES import pymysql from dbutils.pooled_db import PooledDB import logging logger = logging.getLogger(__name__) class MysqlSimipleConn: def __init__(self): # pymysql 连接池 从django settings读取数据库配置,共用 mysql_config = DATABASES["default"] self.pool = PooledDB(pymysql, 5, host=mysql_config['HOST'], user=mysql_config['USER'], passwd=mysql_config['PASSWORD'], db=mysql_config['NAME'], port=int(mysql_config['PORT']), charset=mysql_config["OPTIONS"]['charset']) def query(self, sql: str) -> List: conn = self.pool.connection() cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) result = [] try: cursor.execute(sql) if sql.find('select') != -1 or sql.find("SELECT") != -1: result = cursor.fetchall() elif sql.find("insert") != -1 or sql.find("INSERT") != -1: conn.commit() # 提交的插入才有效果 except Exception as e: conn.rollback() # 失败后就不插入 logger.error(f"{e} : {sql}") return result mysql_conn_instance = MysqlSimipleConn() if __name__ == '__main__': # result = mysql_conn_instance.query("select * from city ;") # print(result) # 测试插入 sql = "insert into test_table (id,name) values ('1','nihao')" result = mysql_conn_instance.query(sql) result = mysql_conn_instance.query("select * from test_table ;") print(result)
{"/weather_cralwer/weather_cralwer/spiders/today_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/db_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/init_db/init_city.py": ["/init_db/mysql_coon.py"], "/weather_cralwer/weather_cralwer/spiders/today_one_city_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/WeatherWeb/weather_show_app/drawviews.py": ["/WeatherWeb/weather_show_app/constant.py", "/WeatherWeb/weather_show_app/models.py"], "/WeatherWeb/weather_show_app/views.py": ["/WeatherWeb/weather_show_app/forms.py", "/WeatherWeb/weather_show_app/kmeans_process.py", "/WeatherWeb/weather_show_app/models.py"], "/init_db/fill_province.py": ["/init_db/mysql_coon.py"], "/init_db/fill_province_test.py": ["/init_db/fill_province.py"], "/weather_cralwer/weather_cralwer/pipelines.py": ["/weather_cralwer/weather_cralwer/items.py"]}
45,109
realzhengyiming/WeatherPlatform
refs/heads/main
/weather_cralwer/weather_cralwer/spiders/today_weather_spider.py
import datetime import json import time from typing import List import scrapy from weather_cralwer.weather_cralwer.clean_util import temperature_process, aqi_process from weather_cralwer.weather_cralwer.db_util import mysql_conn_instance # todo 修好这个东西 找不到爬虫的问题 from weather_cralwer.weather_cralwer.items import DateWeatherItem, HourWeatherItem class ChinaWeatherSpider(scrapy.Spider): name = 'today_weather' allowed_domains = ['weather.com.cn'] head_url = "http://www.weather.com.cn/weather1d/{city_code}.shtml" custom_settings = { 'DOWNLOADER_MIDDLEWARES': { 'weather_cralwer.weather_cralwer.middlewares.ChangeUserAgentMiddleware': 1, }, 'DOWNLOAD_DELAY': 1, 'ITEM_PIPELINES': { 'weather_cralwer.weather_cralwer.pipelines.DateWeatherPipeline': 2, }, # "DOWNLOAD_DELAY": 0.5, } def start_requests(self): all_city_list = mysql_conn_instance.query("select * from City order by is_city desc,id;") # all_city_list = [{"name": "北京", "pinyin": "beijing", "code": '101010100'}] for city_dict in all_city_list: if "pinyin" in city_dict: city_code = city_dict['code'] city_name = city_dict['name'] city_pinyin = city_dict['pinyin'] url = "http://www.weather.com.cn/weather1d/{city_code}.shtml".format(city_code=city_code) yield scrapy.Request(url=url, callback=self.parse, meta={"city_name": city_name, "city_pinyin": city_pinyin, "city_code": city_code}) else: self.logger.info("非国内的跳过") def parse_24hour_data(self, script_string: str): script_string = script_string[script_string.index('=') + 1:-2] # 移除改var data=将其变为json数据 waather_json = json.loads(script_string) today_hour_weather = waather_json['od']['od2'] # 找到当天的数据 today_24hours_weather = [] # 存放当天的数据 count = 0 nowdate = time.strftime('%Y-%m-%d', time.localtime(time.time())) # todo 这儿是做什么的呢。这儿是修改成多表查询,然后才是显示对图进行分析工作。 # now_date = datetime.datetime.now().strftime("%Y-%m-") for i in today_hour_weather: if count <= 23: hour_weather = HourWeatherItem() hour_weather['hour'] = i['od21'] # 添加时间 hour_weather['temperature'] = i['od22'] # 添加当前时刻温度 hour_weather['wind_direction'] = i['od24'] # 添加当前时刻风力方向 hour_weather['wind_power'] = i['od25'] # 添加当前时刻风级 hour_weather["precipitation"] = i['od26'] # 添加当前时刻降水量 hour_weather["relative_humidity"] = i['od27'] # 添加当前时刻相对湿度 hour_weather["AQI"] = aqi_process(i['od28']) # 添加当前时刻控制质量 hour_weather["belong_to_date"] = nowdate # 添加当前时刻控制质量 today_24hours_weather.append(hour_weather) count = count + 1 return today_24hours_weather def parse_7days_data(self, html: str, city_name: str) -> List[DateWeatherItem]: now_date = datetime.datetime.now().strftime('%Y-%m-') future_date = (datetime.date.today() + datetime.timedelta(days=6)).strftime("%Y-%m-") # 如果发现6天后是换月了 html = html.replace("\n", "") html = html[html.find("=") + 1:] html_json = json.loads(html) week_date_weather = html_json.get("7d") week_date_weather_list = [] for day in week_date_weather: day_short_info_item = DateWeatherItem() temp_temperature_list = [t.split(",")[3] for t in day] min_temperature = min(temp_temperature_list) max_temperature = max(temp_temperature_list) temp_day = day[0].split(",") fetch_day = temp_day[0].split("日")[0] date_pattern = future_date if int(fetch_day) <= 7 else now_date day_short_info_item['date'] = date_pattern + fetch_day # 获得 日期的号 如果是月底那还是可以找到 day_short_info_item['state'] = temp_day[2] day_short_info_item['humidity'] = 0.0 day_short_info_item['city_name'] = city_name # 这个是城市名,还需要改成真正的城市对象才可以 day_short_info_item['max_temperature'] = temperature_process(max_temperature) day_short_info_item['min_temperature'] = temperature_process(min_temperature) day_short_info_item['wind_direction'] = temp_day[4] day_short_info_item['wind_power'] = temp_day[5] week_date_weather_list.append(day_short_info_item) # 里面这个是item return week_date_weather_list def parse(self, response): """处理得到有用信息保存数据文件""" all_script_text = response.xpath("//script/text()").getall() # hour3data; observe24h_data dressing_index = response.xpath('//*[@id="chuanyi"]/a/span/text()').extract_first() dressing_index_desc = response.xpath('//*[@id="chuanyi"]/a/p/text()').extract_first() # 穿衣指数描述 observe24h, hour3data = None, None for one in all_script_text: if one.find("var observe24h_data") != -1: observe24h = one # 24小时天气数据 elif one.find("var hour3data") != -1: hour3data = one # 这个是7天天气概括数据 today_24hours_weather = self.parse_24hour_data(observe24h) # 下面爬取7天的数据 # hour3data city_name = response.meta.get("city_name") seven_days_weather_list = self.parse_7days_data(hour3data, city_name) today_weather = seven_days_weather_list[0] # 只能获得当天的穿衣指数,其他天得其他时候进行抓取。 today_weather['dressing_index'] = '' if not dressing_index else dressing_index # 穿衣指数 today_weather['dressing_index_desc'] = "" if not dressing_index_desc else dressing_index_desc today_weather['extend_detail'] = today_24hours_weather # return today_weather_data, week_weather_data for day_weather_item in seven_days_weather_list: yield day_weather_item
{"/weather_cralwer/weather_cralwer/spiders/today_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/db_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/init_db/init_city.py": ["/init_db/mysql_coon.py"], "/weather_cralwer/weather_cralwer/spiders/today_one_city_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/WeatherWeb/weather_show_app/drawviews.py": ["/WeatherWeb/weather_show_app/constant.py", "/WeatherWeb/weather_show_app/models.py"], "/WeatherWeb/weather_show_app/views.py": ["/WeatherWeb/weather_show_app/forms.py", "/WeatherWeb/weather_show_app/kmeans_process.py", "/WeatherWeb/weather_show_app/models.py"], "/init_db/fill_province.py": ["/init_db/mysql_coon.py"], "/init_db/fill_province_test.py": ["/init_db/fill_province.py"], "/weather_cralwer/weather_cralwer/pipelines.py": ["/weather_cralwer/weather_cralwer/items.py"]}
45,110
realzhengyiming/WeatherPlatform
refs/heads/main
/init_db/init_city.py
import sys import os from xpinyin import Pinyin base_dir = '/root/new_tmp_job/WeatherPlatform' sys.path.append(base_dir) from init_db.city_lists import CITY_LIST from init_db.mysql_coon import mysql_conn from init_db.new_city_code import city_and_code def get_city_and_city_pinyin(): city_list = [] with open(os.path.join(base_dir, 'init_db', "city_pinyin_list.txt"), "r", encoding="gbk") as file: for line in file.readlines(): city, pinyin = line.split(" ") pinyin = pinyin.lower().rstrip() # print(city) # print(pinyin) city_list.append([city, pinyin]) return city_list def add_pinyin_to_new_city_code(city_list): for city, pinyin in city_list: for one_city in city_and_code: if one_city['name'] == city: one_city['pinyin'] = pinyin return city_and_code def init_city_table_and_city_data(): result = add_pinyin_to_new_city_code(get_city_and_city_pinyin()) cursor = mysql_conn.cursor() p = Pinyin() print(result) for i in result: sql = "" if 'pinyin' in i: sql = f'insert into City (name,pinyin,code,is_city,direct_city_name) value ("{i["name"]}","{i["pinyin"]}","{i["id"]}",0,"")' else: pinyin = p.get_pinyin(i["name"], "") sql = f'insert into City (name,pinyin,code,is_city,direct_city_name) value ("{i["name"]}","{pinyin}","{i["id"]}",0,"")' try: cursor.execute(sql) mysql_conn.commit() except Exception as e: print(e) print(sql) mysql_conn.close() def fill_city_type(): # is_direct_city cursor = mysql_conn.cursor() cursor.execute("select name from City;") read_all_city_name = cursor.fetchall() for city_name in read_all_city_name: for full_city_name in CITY_LIST: # 有城市的城市列表 if isinstance(city_name, tuple) and len(city_name) == 1: city_name = city_name[0] if full_city_name == city_name + "市": # 对比,然后把地级市的城市列表填充好 try: fill_city_sql = '''update City set direct_city_name = '{full_city_name}', is_city=1 where City.name='{city_name}' ; ''' sql = fill_city_sql.format(full_city_name=full_city_name, city_name=city_name) print(sql) except Exception as e: print(e) print(f"城市全称叫做 - {full_city_name} 城市简称叫做 - {city_name}") return try: cursor.execute(sql) mysql_conn.commit() except Exception as e: print(e) print(sql) mysql_conn.close() if __name__ == '__main__': # 写入城市代码和拼音 # init_city_table_and_city_data() fill_city_type()
{"/weather_cralwer/weather_cralwer/spiders/today_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/db_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/init_db/init_city.py": ["/init_db/mysql_coon.py"], "/weather_cralwer/weather_cralwer/spiders/today_one_city_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/WeatherWeb/weather_show_app/drawviews.py": ["/WeatherWeb/weather_show_app/constant.py", "/WeatherWeb/weather_show_app/models.py"], "/WeatherWeb/weather_show_app/views.py": ["/WeatherWeb/weather_show_app/forms.py", "/WeatherWeb/weather_show_app/kmeans_process.py", "/WeatherWeb/weather_show_app/models.py"], "/init_db/fill_province.py": ["/init_db/mysql_coon.py"], "/init_db/fill_province_test.py": ["/init_db/fill_province.py"], "/weather_cralwer/weather_cralwer/pipelines.py": ["/weather_cralwer/weather_cralwer/items.py"]}
45,111
realzhengyiming/WeatherPlatform
refs/heads/main
/scrapy_main.py
from scrapy.cmdline import execute execute("scrapy crawl today_weather".split())
{"/weather_cralwer/weather_cralwer/spiders/today_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/db_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/init_db/init_city.py": ["/init_db/mysql_coon.py"], "/weather_cralwer/weather_cralwer/spiders/today_one_city_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/WeatherWeb/weather_show_app/drawviews.py": ["/WeatherWeb/weather_show_app/constant.py", "/WeatherWeb/weather_show_app/models.py"], "/WeatherWeb/weather_show_app/views.py": ["/WeatherWeb/weather_show_app/forms.py", "/WeatherWeb/weather_show_app/kmeans_process.py", "/WeatherWeb/weather_show_app/models.py"], "/init_db/fill_province.py": ["/init_db/mysql_coon.py"], "/init_db/fill_province_test.py": ["/init_db/fill_province.py"], "/weather_cralwer/weather_cralwer/pipelines.py": ["/weather_cralwer/weather_cralwer/items.py"]}
45,112
realzhengyiming/WeatherPlatform
refs/heads/main
/spider_schedule.py
# 写一个简单的定时任务,让爬虫自动启动吧 import datetime import subprocess import time import schedule from scrapy.cmdline import execute def spider_schedule_job(): # 启动爬虫呢 print(f"爬虫已启动,启动时间{datetime.datetime.now()}") # execute("scrapy crawl today_weather".split()) # 这样好像是不行的 cmdline = ''' cd /root/new_tmp_job/WeatherPlatform && conda activate weather && scrapy crawl today_weather ''' cmdline = "date" result = subprocess.Popen(cmdline) # system(cmdline) print(result) def execute_spider(): # shell执行的时候提前 使用指定路径下(虚拟环境下的python) execute('scrapy crawl today_weather'.split(" ")) if __name__ == '__main__': SCHEDULE_TIME = "01:00" # 每天这个时候爬虫进行更新 schedule.every().day.at(SCHEDULE_TIME).do(execute_spider) print(f"开始执行,现在时间是 {datetime.datetime.now()}") while True: schedule.run_pending() time.sleep(1) # execute_spider()
{"/weather_cralwer/weather_cralwer/spiders/today_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/db_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/init_db/init_city.py": ["/init_db/mysql_coon.py"], "/weather_cralwer/weather_cralwer/spiders/today_one_city_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/WeatherWeb/weather_show_app/drawviews.py": ["/WeatherWeb/weather_show_app/constant.py", "/WeatherWeb/weather_show_app/models.py"], "/WeatherWeb/weather_show_app/views.py": ["/WeatherWeb/weather_show_app/forms.py", "/WeatherWeb/weather_show_app/kmeans_process.py", "/WeatherWeb/weather_show_app/models.py"], "/init_db/fill_province.py": ["/init_db/mysql_coon.py"], "/init_db/fill_province_test.py": ["/init_db/fill_province.py"], "/weather_cralwer/weather_cralwer/pipelines.py": ["/weather_cralwer/weather_cralwer/items.py"]}
45,113
realzhengyiming/WeatherPlatform
refs/heads/main
/weather_cralwer/weather_cralwer/spiders/today_one_city_weather_spider.py
import datetime import json import time from typing import List import scrapy from weather_cralwer.weather_cralwer.clean_util import temperature_process, aqi_process from weather_cralwer.weather_cralwer.items import DateWeatherItem, HourWeatherItem class ChinaOneWeatherSpider(scrapy.Spider): name = 'baidu' allowed_domains = ['*'] start_urls = [ "http://weathernew.pae.baidu.com/weathernew/pc?query=%E6%83%A0%E5%B7%9E%E5%A4%A9%E6%B0%94&srcid=4982&city_name=%E6%B7%B1%E5%9C%B3&province_name=%E5%B9%BF%E4%B8%9C" ] custom_settings = { 'DOWNLOADER_MIDDLEWARES': { 'weather_cralwer.weather_cralwer.middlewares.ChangeUserAgentMiddleware': 1, }, 'DOWNLOAD_DELAY': 1, 'ITEM_PIPELINES': { 'weather_cralwer.weather_cralwer.pipelines.DateWeatherPipeline': 2, }, # "DOWNLOAD_DELAY": 0.5, } def __init__(self, city_id=None, *args, **kwargs): super(ChinaOneWeatherSpider, self).__init__(*args, **kwargs) self.city_id = city_id def parse_24hour_data(self, script_string: str): script_string = script_string[script_string.index('=') + 1:-2] # 移除改var data=将其变为json数据 waather_json = json.loads(script_string) today_hour_weather = waather_json['od']['od2'] # 找到当天的数据 today_24hours_weather = [] # 存放当天的数据 count = 0 nowdate = time.strftime('%Y-%m-%d', time.localtime(time.time())) # todo 这儿是做什么的呢。这儿是修改成多表查询,然后才是显示对图进行分析工作。 # now_date = datetime.datetime.now().strftime("%Y-%m-") for i in today_hour_weather: if count <= 23: hour_weather = HourWeatherItem() hour_weather['hour'] = i['od21'] # 添加时间 hour_weather['temperature'] = i['od22'] # 添加当前时刻温度 hour_weather['wind_direction'] = i['od24'] # 添加当前时刻风力方向 hour_weather['wind_power'] = i['od25'] # 添加当前时刻风级 hour_weather["precipitation"] = i['od26'] # 添加当前时刻降水量 hour_weather["relative_humidity"] = i['od27'] # 添加当前时刻相对湿度 hour_weather["AQI"] = aqi_process(i['od28']) # 添加当前时刻控制质量 hour_weather["belong_to_date"] = nowdate # 添加当前时刻控制质量 today_24hours_weather.append(hour_weather) count = count + 1 return today_24hours_weather def parse_7days_data(self, html: str, city_name: str) -> List[DateWeatherItem]: now_date = datetime.datetime.now().strftime('%Y-%m-') html = html.replace("\n", "") html = html[html.find("=") + 1:] html_json = json.loads(html) week_date_weather = html_json.get("7d") week_date_weather_list = [] for day in week_date_weather: day_short_info_item = DateWeatherItem() temp_temperature_list = [t.split(",")[3] for t in day] min_temperature = min(temp_temperature_list) max_temperature = max(temp_temperature_list) temp_day = day[0].split(",") day_short_info_item['date'] = now_date + temp_day[0].split("日")[0] # 获得 日期的号 day_short_info_item['state'] = temp_day[2] day_short_info_item['humidity'] = 0.0 day_short_info_item['city_name'] = city_name # 这个是城市名,还需要改成真正的城市对象才可以 day_short_info_item['max_temperature'] = temperature_process(max_temperature) day_short_info_item['min_temperature'] = temperature_process(min_temperature) day_short_info_item['wind_direction'] = temp_day[4] day_short_info_item['wind_power'] = temp_day[5] week_date_weather_list.append(day_short_info_item) # 里面这个是item return week_date_weather_list def parse(self, response): # print(response.text) """处理得到有用信息保存数据文件""" status = response.xpath('//div[@class="zhishu-box"]//text()').get_all() # hour3data; observe24h_data print("----------") print(status)
{"/weather_cralwer/weather_cralwer/spiders/today_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/db_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/init_db/init_city.py": ["/init_db/mysql_coon.py"], "/weather_cralwer/weather_cralwer/spiders/today_one_city_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/WeatherWeb/weather_show_app/drawviews.py": ["/WeatherWeb/weather_show_app/constant.py", "/WeatherWeb/weather_show_app/models.py"], "/WeatherWeb/weather_show_app/views.py": ["/WeatherWeb/weather_show_app/forms.py", "/WeatherWeb/weather_show_app/kmeans_process.py", "/WeatherWeb/weather_show_app/models.py"], "/init_db/fill_province.py": ["/init_db/mysql_coon.py"], "/init_db/fill_province_test.py": ["/init_db/fill_province.py"], "/weather_cralwer/weather_cralwer/pipelines.py": ["/weather_cralwer/weather_cralwer/items.py"]}
45,114
realzhengyiming/WeatherPlatform
refs/heads/main
/WeatherWeb/analysis/graph_api_view.py
# 怎么弄出一个统一的接口呢,或者就弄一个统一的打包装饰器 import json from django.http import HttpResponse from rest_framework.views import APIView from analysis.graph_view import bar_base, GeoMap def response_as_json(data): json_str = json.dumps(data) response = HttpResponse( json_str, content_type="application/json", ) response["Access-Control-Allow-Origin"] = "*" return response def json_response(data, code=200): data = { "code": code, "msg": "success", "data": data, } return response_as_json(data) def json_error(error_string="error", code=500, **kwargs): data = { "code": code, "msg": error_string, "data": {} } data.update(kwargs) return response_as_json(data) JsonResponse = json_response JsonError = json_error # 下面开始是各个api 视图 class BarView(APIView): def get(self, request, *args, **kwargs): return JsonResponse(json.loads(bar_base())) # 这是一个接口,是需要写url映射滴,那怎么办呢 class GeoView(APIView): def get(self, request, *args, **kwargs): return JsonResponse(json.loads(GeoMap())) # 这是一个接口,是需要写url映射滴,那怎么办呢
{"/weather_cralwer/weather_cralwer/spiders/today_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/db_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/init_db/init_city.py": ["/init_db/mysql_coon.py"], "/weather_cralwer/weather_cralwer/spiders/today_one_city_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/WeatherWeb/weather_show_app/drawviews.py": ["/WeatherWeb/weather_show_app/constant.py", "/WeatherWeb/weather_show_app/models.py"], "/WeatherWeb/weather_show_app/views.py": ["/WeatherWeb/weather_show_app/forms.py", "/WeatherWeb/weather_show_app/kmeans_process.py", "/WeatherWeb/weather_show_app/models.py"], "/init_db/fill_province.py": ["/init_db/mysql_coon.py"], "/init_db/fill_province_test.py": ["/init_db/fill_province.py"], "/weather_cralwer/weather_cralwer/pipelines.py": ["/weather_cralwer/weather_cralwer/items.py"]}
45,115
realzhengyiming/WeatherPlatform
refs/heads/main
/WeatherWeb/weather_show_app/drawviews.py
import datetime import json import time import numpy as np import pandas as pd from django.core.cache import cache # 导入缓存对象,redis存储 from django.db import connection from django.db.models import Count # 直接使用models中的统计类来进行统计查询操作 from django.http import HttpResponse from pyecharts import options as opts from pyecharts.charts import Bar, Pie, Line, Geo, Map, Radar from pyecharts.globals import ThemeType, ChartType from rest_framework.views import APIView from .constant import ALL_DIRECTION_MAPPING_DICT from .models import DateWeather, City def fetchall_sql(sql) -> dict: # 这儿唯一有一个就是显示页面的 with connection.cursor() as cursor: cursor.execute(sql) row = cursor.fetchall() return row def fetchall_sql_dict(sql) -> [dict]: # 这儿唯一有一个就是显示页面的 with connection.cursor() as cursor: cursor.execute(sql) columns = [col[0] for col in cursor.description] # 提取出column_name return [dict(zip(columns, row)) for row in cursor.fetchall()] def response_as_json(data): json_str = json.dumps(data) response = HttpResponse( json_str, content_type="application/json", ) response["Access-Control-Allow-Origin"] = "*" return response def json_response(data, code=200): data = { "code": code, "msg": "success", "data": data, } return response_as_json(data) def json_error(error_string="error", code=500, **kwargs): data = { "code": code, "msg": error_string, "data": {} } data.update(kwargs) return response_as_json(data) JsonResponse = json_response JsonError = json_error # 数据概略处的图 最近7天爬虫数据爬取 def bar_base() -> Bar: nowdate = time.strftime('%Y-%m-%d', time.localtime(time.time())) count_total_city = DateWeather.objects.filter(date=nowdate).values("city").annotate( count=Count("city")).order_by("-count") c = ( Bar(init_opts=opts.InitOpts(theme=ThemeType.WONDERLAND)) .add_xaxis([city['city'] for city in count_total_city]) .add_yaxis("房源数量", [city['count'] for city in count_total_city]) .set_global_opts(title_opts=opts.TitleOpts(title="今天城市房源数量", subtitle="如图"), xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=-90)), ) .set_global_opts( datazoom_opts={'max_': 2, 'orient': "horizontal", 'range_start': 10, 'range_end': 20, 'type_': "inside"}) .dump_options_with_quotes() ) return c class ChartView(APIView): def get(self, request, *args, **kwargs): return JsonResponse(json.loads(bar_base())) # 这儿这个是返回json数据用来装到bar中的 class PieView(APIView): # 房型饼图 def get(self, request, *args, **kwargs): result = fetchall_sql( '''select state,count(state) counter from (select distinct id ,state from DateWeather group by id,state ) hello group by state order by counter''') c = ( Pie() .add("", [z for z in zip([i[0] for i in result], [i[1] for i in result])]) .set_global_opts(title_opts=opts.TitleOpts(title="天气类型"), legend_opts=opts.LegendOpts(pos_left="15%", type_='scroll', is_show=False), ) .set_series_opts(label_opts=opts.LabelOpts( formatter="{b}: {c} | {d}%", )) .dump_options_with_quotes() ) return JsonResponse(json.loads(c)) class timeLineView(APIView): # todo 改成了7天内,全国各地多条曲线,每个曲线是一种天气状态的数量。 应该选择原本是line 的图来直接修改好一些,不然自己容易有些乱 def get(self, request, *args, **kwargs): # week_name_list = getLatestSevenDay() # 获得最近七天的日期 时间列折线图 # 七天前的那个日期 today = datetime.datetime.now() # // 计算偏移量 offset = datetime.timedelta(days=-6) # // 获取想要的日期的时间 re_date = (today + offset).strftime('%Y-%m-%d') house_sevenday = DateWeather.objects.filter(date__gte=re_date).values("date"). \ annotate(count=Count("date")).order_by("date") week_name_list = [day['date'] for day in house_sevenday] date_count = [day['count'] for day in house_sevenday] c = ( Line(init_opts=opts.InitOpts(width="1600px", height="800px")) .add_xaxis(xaxis_data=week_name_list) .add_yaxis( series_name="抓取的数量", # y_axis=high_temperature, y_axis=date_count, markpoint_opts=opts.MarkPointOpts( data=[ opts.MarkPointItem(type_="max", name="最大值"), opts.MarkPointItem(type_="min", name="最小值"), ] ), markline_opts=opts.MarkLineOpts( data=[opts.MarkLineItem(type_="average", name="平均值")] ), ) .set_global_opts( title_opts=opts.TitleOpts(title="最近七天抓取情况", subtitle=""), xaxis_opts=opts.AxisOpts(type_="category", boundary_gap=False), ) .dump_options_with_quotes() ) return JsonResponse(json.loads(c)) class drawMap(APIView): def get(self, request, *args, **kwargs): result = cache.get('weather_city', None) # 使用缓存,可以共享真好。 if result is None: # 如果无,则向数据库查询数据 print("读取缓存中的城市") result = fetchall_sql( """select name, count(name) as counter from ( select belong_province as name from DateWeather left join City on DateWeather.city_id = City.id where name!='' ) as t where name<>'' group by name;""") else: pass province_names = [i[0].replace("市", "") .replace("省", "") .replace("回族自治区", "") .replace("壮族自治区", "") .replace("维吾尔自治区", "") .replace("自治区", "") .replace('特别行政区', '') for i in result] province_names_number = [i[1] for i in result] max_total_size = max(province_names_number) zip_data = [list(z) for z in zip(province_names, province_names_number)] c = ( Map() .add(series_name="天气数据省份分布", data_pair=zip_data, maptype="china", zoom=1, center=[105, 38]) .set_global_opts( title_opts=opts.TitleOpts(title="天气数据省份分布"), visualmap_opts=opts.VisualMapOpts(max_=max_total_size, is_piecewise=False) ) .dump_options_with_quotes() ) return JsonResponse(json.loads(c)) class get_today_aqi_bar(APIView): # 按月份分,或者按年分 def get(self, request, *args, **kwargs): city_id = request.GET.get("city_id") today_date = datetime.date.today() select_date = request.GET.get("select_date", today_date) if not city_id: city_id = City.objects.get(name="茂名").id result = fetchall_sql_dict( f'''select * from HourWeather where weather_id = ( select id from DateWeather where city_id=( select id from City where id='{city_id}') and date='{select_date}') and belong_to_date ='{select_date}' order by hour ; ''') temp_df = pd.DataFrame(result) # 都使用df来进行处理和显示 count = 0 for i in list(temp_df.AQI.values): if i != 0: break else: count += 1 if count >= 24: # 如果24小时的都为0 pass else: temp_df = temp_df.replace(0, np.nan) temp_df['AQI'].fillna((temp_df['AQI'].mean()), inplace=True) print(temp_df) hour_list = ['0点', "1点", "2点", "3点", "4点", '5点', '6点', '7点', '8点', '9点', '10点', '11点', '12点', '13点', '14点', '15点', '16点', '17点', '18点', '19点', '20点', '21点', '22点', '23点'] c = ( Bar() .add_xaxis(hour_list) .add_yaxis("AQI", [int(i) for i in list(temp_df.AQI.values)]) .set_global_opts(title_opts=opts.TitleOpts(title="24小时空气质量"), datazoom_opts=opts.DataZoomOpts(), xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=-90)), ) .set_global_opts(datazoom_opts={'orient': "horizontal", 'range_start': 1, 'range_end': 8, 'type_': "inside"}) .dump_options_with_quotes() ) return JsonResponse(json.loads(c)) class get_today_average_humity(APIView): # 按月份分,或者按年分 def get(self, request, *args, **kwargs): print("水球图") city_id = request.GET.get("city_id") today_date = datetime.date.today() select_date = request.GET.get("select_date", today_date) if not city_id: city_id = City.objects.get(name="茂名").id result = fetchall_sql_dict( f'''select * from HourWeather where weather_id = ( select id from DateWeather where city_id=( select id from City where id='{city_id}') and date='{select_date}') and belong_to_date ='{select_date}' order by hour ; ''') temp_df = pd.DataFrame(result) # 都使用df来进行处理和显示 temp_df = temp_df.replace(0, np.nan) temp_df['relative_humidity'].fillna((temp_df['relative_humidity'].mean()), inplace=True) relative_humidity = round(temp_df['relative_humidity'].mean() * 0.01, 2) from pyecharts import options as opts from pyecharts.charts import Liquid c = ( Liquid() .add("lq", [relative_humidity, 0.6, 0.7], is_outline_show=False) .set_global_opts(title_opts=opts.TitleOpts(title="24小时平均湿度")) .dump_options_with_quotes() ) return JsonResponse(json.loads(c)) class wind_graph(APIView): def get(self, request, *args, **kwargs): city_id = request.GET.get("city_id") today_date = datetime.date.today() select_date = request.GET.get("select_date", today_date) if not city_id: city_id = City.objects.get(name="茂名").id result = fetchall_sql_dict( f'''select * from HourWeather where weather_id = ( select id from DateWeather where city_id=( select id from City where id='{city_id}') and date='{select_date}') and belong_to_date ='{select_date}' order by hour ; ''') temp_df = pd.DataFrame(result) # 都使用df来进行处理和显示 today_24hour_winds = temp_df[['wind_power', "wind_direction", "hour"]] today_24hour_winds['hour'] = today_24hour_winds['hour'].apply(int) rader = Radar(init_opts=opts.InitOpts(width="1280px", height="720px")).add_schema( schema=[ opts.RadarIndicatorItem(name="北风", max_=10), opts.RadarIndicatorItem(name="东北风", max_=10), opts.RadarIndicatorItem(name="东风", max_=10), opts.RadarIndicatorItem(name="东南风", max_=10), opts.RadarIndicatorItem(name="南风", max_=10), opts.RadarIndicatorItem(name="西南风", max_=10), opts.RadarIndicatorItem(name="西风", max_=10), opts.RadarIndicatorItem(name="西北风", max_=10), ], splitarea_opt=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1) ), ) for index, row in today_24hour_winds.iterrows(): wind_power, wind_direction, hour = list(row) temp_hour_wind = [0 for i in range(8)] temp_hour_wind[ALL_DIRECTION_MAPPING_DICT[wind_direction]] = wind_power rader.add(series_name=f"{hour + 1}时", data=[temp_hour_wind]) c = (rader.set_series_opts(label_opts=opts.LabelOpts(is_show=True)) .set_global_opts( legend_opts=opts.LegendOpts()) .dump_options_with_quotes()) return JsonResponse(json.loads(c)) class today_temperature_detail_line(APIView): def get(self, request, *args, **kwargs): city_id = request.GET.get("city_id") now_date = datetime.datetime.now().date() select_date = request.GET.get("select_date", now_date) if not city_id: city_id = City.objects.get(name="茂名").id print(f"温度获得的城市id {city_id}") result = fetchall_sql_dict( f'''select * from HourWeather where weather_id = ( select id from DateWeather where city_id={city_id} and date='{select_date}' ) and belong_to_date ='{select_date}' order by hour ; ''') # 用line? # 按24小时进行排序才可以 temp_df = pd.DataFrame(result) week_name_list = ['0点', "1点", "2点", "3点", "4点", '5点', '6点', '7点', '8点', '9点', '10点', '11点', '12点', '13点', '14点', '15点', '16点', '17点', '18点', '19点', '20点', '21点', '22点', '23点'] high_temperature = [i for i in list(temp_df.temperature)] # 改成按当天的 按 1~23 , # low_temperature = [i for i in list(temp_df.relative_humidity)] c = ( Line(init_opts=opts.InitOpts(width="1600px", height="800px")) # 为什么没反应 .add_xaxis(xaxis_data=week_name_list) .add_yaxis( series_name="最高气温", y_axis=high_temperature, markpoint_opts=opts.MarkPointOpts( data=[ opts.MarkPointItem(type_="max", name="最大值"), opts.MarkPointItem(type_="min", name="最小值"), ] ), markline_opts=opts.MarkLineOpts( data=[opts.MarkLineItem(type_="average", name="平均值")] ), ) .set_global_opts( title_opts=opts.TitleOpts(title="当天24小时温度情况", subtitle="每小时温度"), tooltip_opts=opts.TooltipOpts(trigger="axis"), toolbox_opts=opts.ToolboxOpts(is_show=True), xaxis_opts=opts.AxisOpts(type_="category", boundary_gap=False), ) .dump_options_with_quotes() ) return JsonResponse(json.loads(c))
{"/weather_cralwer/weather_cralwer/spiders/today_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/db_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/init_db/init_city.py": ["/init_db/mysql_coon.py"], "/weather_cralwer/weather_cralwer/spiders/today_one_city_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/WeatherWeb/weather_show_app/drawviews.py": ["/WeatherWeb/weather_show_app/constant.py", "/WeatherWeb/weather_show_app/models.py"], "/WeatherWeb/weather_show_app/views.py": ["/WeatherWeb/weather_show_app/forms.py", "/WeatherWeb/weather_show_app/kmeans_process.py", "/WeatherWeb/weather_show_app/models.py"], "/init_db/fill_province.py": ["/init_db/mysql_coon.py"], "/init_db/fill_province_test.py": ["/init_db/fill_province.py"], "/weather_cralwer/weather_cralwer/pipelines.py": ["/weather_cralwer/weather_cralwer/items.py"]}
45,116
realzhengyiming/WeatherPlatform
refs/heads/main
/WeatherWeb/weather_show_app/templatetags/city_tags.py
# -*- coding: utf-8 -*- """ ------------------------------------------------- File Name: city_tags Description : Author : zhengyimiing date: 2020/4/28 ------------------------------------------------- Change Activity: 2020/4/28 ------------------------------------------------- """ __author__ = 'zhengyimiing' import datetime from django import template from weather_show_app.constant import WALK_OUT_GUIDE_DICT from weather_show_app.models import City, DateWeather register = template.Library() @register.inclusion_tag('weather_show_app/select.html') def get_all_city(): result = City.objects.all() return {'allcity': result, } @register.inclusion_tag('weather_show_app/select_cityName.html') def get_all_cityName(): result = City.objects.all() return {'allcity': result, } @register.filter(name='get_city_today_weather') def get_city_today_weather(city_id): city = City.objects.get(id=city_id) now_date = datetime.datetime.now().date() today_weather = DateWeather.objects.get(city_id=city.id, date=now_date) return today_weather @register.filter(name='get_city_by_id') def get_city_by_id(city_id): city = City.objects.get(id=city_id) return city.name @register.filter(name='get_max_temperature') def get_max_temperature(today_weather): return today_weather.max_temperature @register.filter(name='get_min_temperature') def get_min_temperature(today_weather): return today_weather.min_temperature @register.filter(name='get_state') def get_state(today_weather): return today_weather.state # 出行指南 @register.filter(name='state_to_outdoor_guide') def state_to_outdoor_guide(state): if not state: return "无推荐" return WALK_OUT_GUIDE_DICT[state] # 穿衣指数 @register.filter(name='wear_clothing_guide') def wear_clothing_guide(today_weather): mean_temperature = (today_weather.min_temperature + today_weather.max_temperature) / 2 if mean_temperature <= 0: return "棉衣、冬大衣、皮夹克、厚呢外套、呢帽、手套、羽绒服、裘皮大衣" elif 0 < mean_temperature <= 5: return '厚呢外套、呢帽、手套、羽绒服、皮袄' elif 5 < mean_temperature <= 10: return "棉衣、冬大衣" elif 10 < mean_temperature <= 20: return "风衣、大衣" elif 20 < mean_temperature <= 25: return '棉麻面料的衬衫、薄长裙、薄T恤' elif 25 < mean_temperature < 30: return '轻棉织物制作的短衣、短裙、薄短裙、短裤' else: return "没有推荐" # 穿衣指数 @register.filter(name='clean_mydate') def clean_mydate(date_str): date_str = str(date_str) date_str = date_str.replace("年", "-").replace("月", "-").replace("日", "-") return date_str
{"/weather_cralwer/weather_cralwer/spiders/today_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/db_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/init_db/init_city.py": ["/init_db/mysql_coon.py"], "/weather_cralwer/weather_cralwer/spiders/today_one_city_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/WeatherWeb/weather_show_app/drawviews.py": ["/WeatherWeb/weather_show_app/constant.py", "/WeatherWeb/weather_show_app/models.py"], "/WeatherWeb/weather_show_app/views.py": ["/WeatherWeb/weather_show_app/forms.py", "/WeatherWeb/weather_show_app/kmeans_process.py", "/WeatherWeb/weather_show_app/models.py"], "/init_db/fill_province.py": ["/init_db/mysql_coon.py"], "/init_db/fill_province_test.py": ["/init_db/fill_province.py"], "/weather_cralwer/weather_cralwer/pipelines.py": ["/weather_cralwer/weather_cralwer/items.py"]}
45,117
realzhengyiming/WeatherPlatform
refs/heads/main
/weather_cralwer/weather_cralwer/clean_util.py
def temperature_process(valid_temperature: str) -> float: valid_temperature = valid_temperature.replace("℃", "") return float(valid_temperature) def aqi_process(valid_aqi: str) -> float: if not valid_aqi: return 0.0 else: return float(valid_aqi)
{"/weather_cralwer/weather_cralwer/spiders/today_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/db_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/init_db/init_city.py": ["/init_db/mysql_coon.py"], "/weather_cralwer/weather_cralwer/spiders/today_one_city_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/WeatherWeb/weather_show_app/drawviews.py": ["/WeatherWeb/weather_show_app/constant.py", "/WeatherWeb/weather_show_app/models.py"], "/WeatherWeb/weather_show_app/views.py": ["/WeatherWeb/weather_show_app/forms.py", "/WeatherWeb/weather_show_app/kmeans_process.py", "/WeatherWeb/weather_show_app/models.py"], "/init_db/fill_province.py": ["/init_db/mysql_coon.py"], "/init_db/fill_province_test.py": ["/init_db/fill_province.py"], "/weather_cralwer/weather_cralwer/pipelines.py": ["/weather_cralwer/weather_cralwer/items.py"]}
45,118
realzhengyiming/WeatherPlatform
refs/heads/main
/WeatherWeb/weather_show_app/kmeans_process.py
# 这个是进行无监督聚类处理的东西 import datetime import pandas as pd from sklearn.cluster import KMeans from weather_show_app.models import City, DateWeather def one_hot_col_process(df, col_name): # 对分类变量做one-hot处理 one_hot_cols = pd.get_dummies(df[col_name]) df = df.join(one_hot_cols) df = df.drop(col_name, axis=1) return df # 这儿进行 数据清洗操作 def get_similarity_city(df_one_hot_processed): ''' 这儿输出的df 是经过了把city_id替换成city_name, 并且经过了one-hot 对城市列表处理的聚类后的 date_weather的df ''' temp_df = df_one_hot_processed[CITY_TYPES] # 截取只有city one-hot的列(27开始是城市列) temp_df_col = list(temp_df.columns) # 按行读,如果找到所在行为1 的就取columns名字 not_zero = [] for index, row in temp_df.iterrows(): for row_index, value in enumerate(row): if value == 1 or value == "1": col_name = temp_df_col[row_index] not_zero.append(col_name) return not_zero # 相似的城市列表返回回来了 # 初始化,先读取出来 SQL_PATTERN = "select * from City;" HOUR_WEATHER_SQL = '''select * from HourWeather ;''' DATE_WEATHER_SQL = '''select * from DateWeather where date='2021-05-03' and city_id in ( select id from City where is_city=true)''' all_citys = City.objects.all() city_table = pd.DataFrame.from_records(all_citys.values()) some_citys = City.objects.filter(is_city=True).order_by("-id") all_date_weathers = DateWeather.objects.filter(date=datetime.datetime.today(), city__in=some_citys) date_weather_table = pd.DataFrame.from_records(all_date_weathers.values()) # 合并多个表,然后做分析处理 city_table = city_table.rename(columns={"id": "city_id"}) date_weather_with_city_name = pd.merge(date_weather_table, city_table, how='left', on='city_id') # 提前配置好的常量 NEED_TRAIN_COLS = ['state', 'max_temperature', 'min_temperature', 'wind_power', 'wind_direction', 'name'] WEATHER_TYPES = list(date_weather_with_city_name['state'].unique()) CITY_TYPES = list(date_weather_with_city_name['name'].unique()) NEED_ONE_HOT_COLS = ['state', 'wind_power', 'wind_direction', 'name'] df = date_weather_with_city_name[NEED_TRAIN_COLS] # 把df分类变量处理成one hot for col_name in NEED_ONE_HOT_COLS: df = one_hot_col_process(df, col_name) # 现在是处理后的样子了 kmeans_model = KMeans(n_clusters=10, init='k-means++', random_state=11) fit_clf = kmeans_model.fit(df) # 这儿开始是将传过来的df处理成 待查询预测的分类 def get_similarity_city_controller(city_id): today_city_weather_result = DateWeather.objects.filter(city_id=city_id, date=datetime.datetime.today()) today_city_weather = pd.DataFrame.from_records(today_city_weather_result.values()) today_city_weather = pd.merge(today_city_weather, city_table, how='left', on='city_id') today_city_weather = today_city_weather[NEED_TRAIN_COLS] today_city_weather_cleaned = today_city_weather for col_name in NEED_ONE_HOT_COLS: today_city_weather_cleaned = one_hot_col_process(today_city_weather_cleaned, col_name) # 不行,应该直接从训练好的地方来进行查询 full_columns = list(df.columns) empty_df = pd.DataFrame(columns=full_columns) need_predict_df = pd.concat([empty_df, today_city_weather_cleaned], axis=0).fillna(0) # 也要经过相同的处理 result = fit_clf.predict(need_predict_df) # 获得每一类的相似的城市 classes = list(set(list(result)))[0] res_df = df[(fit_clf.labels_ == classes)] # 同一类的df集合(已经是one——hot后的了 return get_similarity_city(res_df)
{"/weather_cralwer/weather_cralwer/spiders/today_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/db_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/init_db/init_city.py": ["/init_db/mysql_coon.py"], "/weather_cralwer/weather_cralwer/spiders/today_one_city_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/WeatherWeb/weather_show_app/drawviews.py": ["/WeatherWeb/weather_show_app/constant.py", "/WeatherWeb/weather_show_app/models.py"], "/WeatherWeb/weather_show_app/views.py": ["/WeatherWeb/weather_show_app/forms.py", "/WeatherWeb/weather_show_app/kmeans_process.py", "/WeatherWeb/weather_show_app/models.py"], "/init_db/fill_province.py": ["/init_db/mysql_coon.py"], "/init_db/fill_province_test.py": ["/init_db/fill_province.py"], "/weather_cralwer/weather_cralwer/pipelines.py": ["/weather_cralwer/weather_cralwer/items.py"]}
45,119
realzhengyiming/WeatherPlatform
refs/heads/main
/WeatherWeb/analysis/views.py
from django.shortcuts import render # geo graph from pyecharts import options as opts from pyecharts.charts import Geo from pyecharts.datasets import register_url # 做这个前后端分离的步骤是: # 1. 思考,选好大概要用什么可视化的图 # 2. 然后是查看官方文档,复制下源代码 # 2.1 首先是按照官方的。把 对象创建好,比如bar(),然后统一用jsonResponse 装好。 # 2.2 然后是创建好url的映射这个接口的路径和name # 2。3 然后前端使用ajax进行加载。这个加载可以从老的代码那儿抽取出来。 # class IndexView(APIView): # def get(self, request, *args, **kwargs): # return HttpResponse(content=open("analysis/test.html").read()) def IndexView(request): # 测试页 return render(request, 'analysis/test.html')
{"/weather_cralwer/weather_cralwer/spiders/today_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/db_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/init_db/init_city.py": ["/init_db/mysql_coon.py"], "/weather_cralwer/weather_cralwer/spiders/today_one_city_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/WeatherWeb/weather_show_app/drawviews.py": ["/WeatherWeb/weather_show_app/constant.py", "/WeatherWeb/weather_show_app/models.py"], "/WeatherWeb/weather_show_app/views.py": ["/WeatherWeb/weather_show_app/forms.py", "/WeatherWeb/weather_show_app/kmeans_process.py", "/WeatherWeb/weather_show_app/models.py"], "/init_db/fill_province.py": ["/init_db/mysql_coon.py"], "/init_db/fill_province_test.py": ["/init_db/fill_province.py"], "/weather_cralwer/weather_cralwer/pipelines.py": ["/weather_cralwer/weather_cralwer/items.py"]}
45,120
realzhengyiming/WeatherPlatform
refs/heads/main
/WeatherWeb/weather_show_app/models.py
from datetime import date from django.contrib.auth.models import User from django.db import models class DateWeather(models.Model): # 天气概括表 todo 敲里吗,调试一点都不好用!!!!!!!我 class Meta: db_table = 'DateWeather' unique_together = ("date", "city") dressing_index = models.CharField(default="", max_length=50) # 穿衣指数 # todo 保存哪儿需要改成update,看看怎么进行操作。 dressing_index_desc = models.TextField(default="") # 穿衣指数语言描述 # todo 保存哪儿需要改成update,看看怎么进行操作。 humidity = models.FloatField() # 湿度 state = models.TextField() # 晴朗,多云,大风,台风,暴雨,暴雪,~之类的 date = models.DateField() update_date = models.DateField(auto_now=True) max_temperature = models.FloatField() # 最高温和最低温 min_temperature = models.FloatField() wind_power = models.TextField(blank=True, default="") # 风力 wind_direction = models.TextField(blank=True) # 风向 city = models.ForeignKey("City", related_name="City", on_delete=models.CASCADE) # 这个是删除操作 # extend_detail = models.TextField(blank=True) # 这个是json的东西 def __str__(self): return f"{self.date};{self.city}" class HourWeather(models.Model): # h每小时的具体的天气情况 class Meta: db_table = 'HourWeather' Weather = models.ForeignKey("DateWeather", on_delete=models.CASCADE, related_name='DateWeather') belong_to_date = models.DateField(default=date.today) # 这边也需要进行设置,这边的属于谁的日期需要增加。 hour = models.IntegerField() temperature = models.FloatField() # 最高温和最低温 wind_power = models.FloatField(blank=True, default=0.0) # 风力 wind_direction = models.TextField(blank=True) # 风向 precipitation = models.FloatField() relative_humidity = models.IntegerField() AQI = models.IntegerField(blank=True, default=0) # 空气质量 def __str__(self): return f"{self.hour};{self.belong_to_date};{self.Weather}" class City(models.Model): class Meta: db_table = 'City' name = models.CharField(max_length=50, unique=True) # 城市名字 pinyin = models.CharField(max_length=100, blank=True) # 减少冗余的代价是时间代价 code = models.CharField(max_length=20, blank=True) is_city = models.BooleanField(default=False) # 地图只能显示地级市,而无法判断 城市内的区域,比如 南山 direct_city_name = models.CharField(max_length=100, default="") # 增加了城市名,脚本处理写入 location = models.CharField(max_length=150, default="") # 经纬度 belong_province = models.CharField(max_length=100, default="") # 属于的省份 # 对应中国天气网的url code http://www.weather.com.cn/weather/101080101.shtml '''alter table City add COLUMN location varchar(150) default '' ;''' def __str__(self): return f"{self.name};" class Favourite(models.Model): # 收藏夹 class Meta: db_table = 'Favourite' user = models.OneToOneField(User, unique=True, on_delete=models.CASCADE) city = models.ManyToManyField('City', related_name="fav_city") def __str__(self): return f"{self.city};{self.user}"
{"/weather_cralwer/weather_cralwer/spiders/today_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/db_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/init_db/init_city.py": ["/init_db/mysql_coon.py"], "/weather_cralwer/weather_cralwer/spiders/today_one_city_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/WeatherWeb/weather_show_app/drawviews.py": ["/WeatherWeb/weather_show_app/constant.py", "/WeatherWeb/weather_show_app/models.py"], "/WeatherWeb/weather_show_app/views.py": ["/WeatherWeb/weather_show_app/forms.py", "/WeatherWeb/weather_show_app/kmeans_process.py", "/WeatherWeb/weather_show_app/models.py"], "/init_db/fill_province.py": ["/init_db/mysql_coon.py"], "/init_db/fill_province_test.py": ["/init_db/fill_province.py"], "/weather_cralwer/weather_cralwer/pipelines.py": ["/weather_cralwer/weather_cralwer/items.py"]}
45,121
realzhengyiming/WeatherPlatform
refs/heads/main
/WeatherWeb/weather_show_app/forms.py
# -*- coding: utf-8 -*- """ ------------------------------------------------- File Name: forms Description : Author : zhengyimiing date: 2020/3/26 ------------------------------------------------- Change Activity: 2020/3/26 ------------------------------------------------- """ from django.contrib.auth.models import User __author__ = 'zhengyimiing' from django import forms class LoginForm(forms.Form): username = forms.CharField(widget=forms.TextInput(attrs={'class': 'mdui-textfield-input', 'placeholder': "用户名"})) password = forms.CharField( widget=forms.PasswordInput(attrs={'class': 'mdui-textfield-input', 'placeholder': "密码"})) # 密码啊 class RegistrationForm(forms.ModelForm): # 这个是注册表单的,表单继承model就是modelform username = forms.CharField(label="用户名", widget=forms.TextInput(attrs={'class': 'mdui-textfield-input', 'placeholder': "用户名"})) password = forms.CharField(label="密码", widget=forms.PasswordInput(attrs={'class': 'mdui-textfield-input', 'pattern': "^.*(?=.{8,})(?=.*[a-z])(?=.*[A-Z]).*$", 'placeholder': "密码"})) password2 = forms.CharField(label="再次输入密码", widget=forms.PasswordInput(attrs={'class': 'mdui-textfield-input', 'pattern': "^.*(?=.{8,})(?=.*[a-z])(?=.*[A-Z]).*$", 'placeholder': "密码"})) email = forms.CharField(label='邮箱', widget=forms.EmailInput( attrs={'type': "email", 'class': 'mdui-textfield-input', 'placeholder': "密码"}) , error_messages={'required': "邮箱不能为空"}) class Meta: model = User fields = ("username", "email") def clean_password2(self): cd = self.cleaned_data if cd['password'] != cd['password2']: raise forms.ValidationError("两次输入的密码不相同") return cd["password2"]
{"/weather_cralwer/weather_cralwer/spiders/today_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/db_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/init_db/init_city.py": ["/init_db/mysql_coon.py"], "/weather_cralwer/weather_cralwer/spiders/today_one_city_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/WeatherWeb/weather_show_app/drawviews.py": ["/WeatherWeb/weather_show_app/constant.py", "/WeatherWeb/weather_show_app/models.py"], "/WeatherWeb/weather_show_app/views.py": ["/WeatherWeb/weather_show_app/forms.py", "/WeatherWeb/weather_show_app/kmeans_process.py", "/WeatherWeb/weather_show_app/models.py"], "/init_db/fill_province.py": ["/init_db/mysql_coon.py"], "/init_db/fill_province_test.py": ["/init_db/fill_province.py"], "/weather_cralwer/weather_cralwer/pipelines.py": ["/weather_cralwer/weather_cralwer/items.py"]}
45,122
realzhengyiming/WeatherPlatform
refs/heads/main
/WeatherWeb/weather_show_app/views.py
import datetime import json import pandas as pd from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger # 用来分页饿 from django.db import connection from django.db.models import Count # 直接使用models中的统计类来进行统计查询操作 from django.db.models import Q from django.http import HttpResponse from django.shortcuts import render, redirect from rest_framework.views import APIView from .forms import LoginForm, RegistrationForm from .kmeans_process import get_similarity_city_controller from .models import City, DateWeather, Favourite def index(request): return render(request, 'weather_show_app/index_charts.html') @login_required(login_url='/weather/loginpage/') # 默认主页 def detailView(request): # 详情页 house_id = request.GET.get("house_id") houseList = City.objects.filter(Q(house_id=house_id)).order_by("-house_date") labels = houseList[0].house_labels.all() # print(labels) facility = houseList[0].house_facility.all() return render(request, "weather_show_app/index_chartspage_detail.html", context={"house": houseList, "house_id": house_id, "labels": labels, "facility": facility, "app_name": "房源详情" }) def testindex(request): # 测试页 # todo 提取不重复的日期的东西,然后进行年月日绘制图片进行查看可视化,同比环比,这个也是可以的 result = fetchall_sql_dict("SELECT distinct(id),house_firstOnSale FROM `hotelapp_house` ") # print(result) # 然后转换成pandas进行一系列的筛选等 # qs_dataframe = read_frame(qs=result) df = pd.DataFrame(result) # 按月份 df.index = pd.to_datetime(df.house_firstOnSale) return render(request, 'weather_show_app/test.html', context={"article": result}) # @login_required(login_url='/loginpage/') # 详情页 def detaillist(request): # 数据列表页分页 today = datetime.datetime.now().date() date_weathers = DateWeather.objects.filter(date=today).order_by("-id").order_by("city_id") paginator = Paginator(date_weathers, 20) # 2个一页的意思 page = request.GET.get("page") try: current_page = paginator.page(page) date_weathers = current_page.object_list except PageNotAnInteger: current_page = paginator.page(1) date_weathers = current_page.object_list except EmptyPage: current_page = paginator.page(paginator.num_pages) date_weathers = current_page.object_list return render(request, "weather_show_app/index_chartspage_detaillist.html", context={"app_name": "详细数据", "date_weathers": date_weathers, "page": current_page}) # 这两个是必须要带上的属性 def fetchall_sql(sql) -> tuple: # 这儿唯一有一个就是显示页面的 # latest_question_list = KeyWordItem # 换成直接使用sql来进行工作 with connection.cursor() as cursor: cursor.execute(sql) row = cursor.fetchall() # columns = [col[0] for col in cursor.description] # 提取出column_name # return [dict(zip(columns, row)) for row in cursor.fetchall()][0] return row def fetchall_sql_dict(sql) -> [dict]: # 这儿唯一有一个就是显示页面的 # latest_question_list = KeyWordItem # 换成直接使用sql来进行工作 print("check sql") print(sql) with connection.cursor() as cursor: cursor.execute(sql) # row = cursor.fetchall() columns = [col[0] for col in cursor.description] # 提取出column_name return [dict(zip(columns, row)) for row in cursor.fetchall()] # @login_required(login_url='/loginpage/') # 默认主页,主页不用登录,但是收藏夹需要登录 def index(request): # 这儿唯一有一个就是显示页面的 success_info = None if request.GET.get("success_info"): success_info = request.GET.get("success_info") # 总共的城市的数量 count_city = City.objects.all().aggregate(count=Count("name", distinct=True)) # todo 花里胡哨的样式晚点再慢慢调整 count_today = DateWeather.objects.all().aggregate(count=Count("id")) print(count_today) print(count_city) context = { 'app_name': "天气分析", 'count_today': count_today, # None, # count_today 'count_today_city': count_city, # None, # count_today_city, # 今天总共爬了多少个城市 'count_total_city': None, # count_total_city 'success_info': success_info } return render(request, 'weather_show_app/index_chartspage.html', context) def loginPage(request): # 登陆界面的,这个是自定义的 if request.method == "GET": success_info = None if request.session.get("success_info"): success_info = request.session.get("success_info") print("正在输出") print(request.session.get("success_info")) del request.session['success_info'] # 用完就删掉 print("删除后") print(request.session.get("success_info")) login_form = LoginForm() return render(request, 'weather_show_app/loginPage.html', context={'form': login_form, 'success_info': success_info}) if request.method == "POST": login_form = LoginForm(request.POST) # 这个 if login_form.is_valid(): cd = login_form.cleaned_data # 转化成字段来方便提取 user = authenticate(username=cd['username'], password=cd['password']) if user: login(request, user) # return HttpResponse("Wellcome!") return redirect('/') else: return render(request, 'weather_show_app/loginPage.html', context={'form': login_form, "error": "账号或者密码错误!"}) else: error = "请检查输入的账号和密码是否正确" login_form = LoginForm() return render(request, 'weather_show_app/loginPage.html', context={'form': login_form, "error": error}) def register(request): # 注册用户User if request.method == "POST": user_form = RegistrationForm(request.POST) if user_form.is_valid(): new_user = user_form.save(commit=False) new_user.set_password(user_form.cleaned_data["password"]) # new_user. new_user.save() # 这儿放登陆注册的 # loginForm = LoginForm() request.session['success_info'] = 'register_success' return redirect('/loginpage') # todo 用命名空间的方式来进行操作 else: return render(request, "weather_show_app/register.html", {"form": user_form, "error_message": "提交的账号密码不合法"}) # 这个是get的方式进来 else: user_form = RegistrationForm() return render(request, "weather_show_app/register.html", {"form": user_form}) # 这个是get的方式进来 def userLogout(request): # 登出 logout(request) return redirect("/loginpage/") def response_as_json(data): json_str = json.dumps(data) response = HttpResponse( json_str, content_type="application/json", ) response["Access-Control-Allow-Origin"] = "*" return response def json_response(data, code=200): data = { "code": code, "msg": "success", "data": data, } return response_as_json(data) def json_error(error_string="error", code=500, **kwargs): data = { "code": code, "msg": error_string, "data": {} } data.update(kwargs) return response_as_json(data) JsonResponse = json_response JsonError = json_error def today_weather_page(request): city_id = request.GET.get("city_id", 174) # 174 是茂名 city_name = request.GET.get("city_name", None) # 174 是茂名 city = City.objects.filter(name=city_name) if not city: now_city = City.objects.get(id=city_id) else: now_city = city[0] now_date = datetime.datetime.now().strftime('%Y-%m-%d') yesterday = (datetime.date.today() - datetime.timedelta(days=1)).strftime('%Y-%m-%d') select_date = request.GET.get("select_date", now_date) all_citys = City.objects.filter(is_city=True) today_weather = DateWeather.objects.get(city_id=now_city.id, date=select_date) future_date = (datetime.date.today() + datetime.timedelta(days=7)).strftime('%Y-%m-%d') past_dates = (datetime.date.today() - datetime.timedelta(days=7)).strftime('%Y-%m-%d') future_weathers = DateWeather.objects.filter(date__range=(now_date, future_date), city_id=city_id) past_weathers = DateWeather.objects.filter(date__range=(past_dates, yesterday), city_id=city_id).order_by("-date") past_weather_dates = [weather.date for weather in past_weathers] result = get_similarity_city_controller(city_id) return render(request, 'weather_show_app/index_chartspage_today_detail.html', context={"app_name": "指定城市当天天气情况", 'all_citys': all_citys, 'test_vars': result, "select_date": select_date, "city_id": city_id, "now_city": now_city, "today_weather": today_weather, "future_weathers": future_weathers, "past_dates": past_weather_dates}) # 搜索的页面 @login_required(login_url='/loginpage/') # 默认主页 def searchPage(request): return render(request, 'weather_show_app/index_chartspage_search.html', context={"app_name": "查找房源"}) # 详细的页面 # @login_required(login_url='/loginpage/') # 默认主页 def trainPage(request): return render(request, 'weather_show_app/test.html', context={"app_name": "test"}) def genFavtag(city_object: City, date_weather: DateWeather): # 输入一个fav对象,生成一个house tag # todo 收藏夹功能 tag = f'''<tr id='tr-{city_object.id}'> <td>{city_object.id}</td> <td>{city_object.name}</td> <td>{date_weather.state}</td> <td>{date_weather.min_temperature}℃~~{date_weather.max_temperature}℃~</td> <td><a target="_blank" href="/host/?city_id={city_object.id}">{city_object.name}</a></td> <td> <button onclick="delete_btn({city_object.id})" id="{city_object.name}" name="del_button" class="mdui-color-theme-accent mdui-btn mdui-btn-icon mdui-ripple mdui-ripple-white"> <i class="mdui-icon material-icons">delete_forever</i></button></td> </tr>''' return tag # 加入收藏和删除收藏的功能 class favouriteHandler(APIView): # 使用不同的试图来进行封装 def get(self, request, *args, **kwargs): # print("get 进来了") method = self.request.query_params.get('method', None) if method is not None: username = self.request.query_params.get("username", None) if not username: return json_response({"result": "请您先登录呢😯", 'tag': ""}) city_id = self.request.query_params.get("city_id", 0) if method == "add": if username != 0 and city_id != 0: import traceback user = User.objects.filter(username=username).first() # city = City.objects.filter(id=city_id).first() # 找到这个房子 date_weather = DateWeather.objects.filter(city_id=city.id, date=datetime.datetime.now().date()).first() if user is not None and city is not None: try: f1 = Favourite.objects.get(user=user) # 找到一个收藏夹对象 # 这儿可能重复 for i in list(f1.city.all()): if str(i.id) == city_id: return json_response({"result": "已在收藏夹 √ 😀", 'tag': ""}) f1.city.add(city) f1.save() # 增加收藏 return json_response({"result": "加入收藏 √ 👌", 'tag': genFavtag(city, date_weather)}) except Favourite.DoesNotExist: # 创建 # 没有收藏时候 print(traceback.print_exc()) try: f1 = Favourite.objects.create(user=user) f1.city.add(city) f1.save() return json_response({"result": "加入收藏 √ 👌", 'tag': genFavtag(city, date_weather)}) except Exception as e: print(e) print(traceback.print_exc()) print("请检查") except Exception as e: print(e) return json_response({"result": "出现问题", 'tag': ""}) if method == "del": user = User.objects.filter(username=username).first() # city = City.objects.filter(id=city_id).first() # 找到这个房子 if user is not None and city is not None: try: f1 = Favourite.objects.get(user=user) # 找到一个收藏夹对象 f1.city.remove(city) f1.save() # 增加收藏 return json_response({"result": "删除成功 √ 👌"}) except Favourite.DoesNotExist: # 创建 print("没有收藏夹") else: return json_response({"result": "未找到此城市!!!"}) else: return json_response({"result": "未找到参数"}) def post(self, request, *args, **kwargs): return json_response({"result": "请通过get"}) # 这个组件是组装搜索结果的 def maketable(result): head = ''' <table class="mdui-table"> <thead> <tr> <th>价格(¥)</th> <th>房源名</th> <th>地理位置</th> <th>喜欢数</th> <th>预览</th> </tr> </thead> <tbody> ''' temp = "" for object in result: temp += f''' <tr> <td>{object['house_discountprice']}</td> <td ><a href="/weather_show_app/detail/?house_id={object['house_id']}" target="_blank" >{object['house_title']}</a></td> <th>{object['house_location_text']}</th> <td>{object['house_favcount']}</td> <td style="width:300px;height:auto;"><img class="mdui-img-fluid" src="{object['house_img']}" /></td> </tr> ''' tail = '''</tbody></table>''' return head + temp + tail
{"/weather_cralwer/weather_cralwer/spiders/today_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/db_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/init_db/init_city.py": ["/init_db/mysql_coon.py"], "/weather_cralwer/weather_cralwer/spiders/today_one_city_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/WeatherWeb/weather_show_app/drawviews.py": ["/WeatherWeb/weather_show_app/constant.py", "/WeatherWeb/weather_show_app/models.py"], "/WeatherWeb/weather_show_app/views.py": ["/WeatherWeb/weather_show_app/forms.py", "/WeatherWeb/weather_show_app/kmeans_process.py", "/WeatherWeb/weather_show_app/models.py"], "/init_db/fill_province.py": ["/init_db/mysql_coon.py"], "/init_db/fill_province_test.py": ["/init_db/fill_province.py"], "/weather_cralwer/weather_cralwer/pipelines.py": ["/weather_cralwer/weather_cralwer/items.py"]}
45,123
realzhengyiming/WeatherPlatform
refs/heads/main
/WeatherWeb/analysis/graph_view.py
from random import randrange from pyecharts import options as opts from pyecharts.charts import Bar, Geo from pyecharts.datasets import register_url def bar_base() -> Bar: c = ( Bar() .add_xaxis(["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]) .add_yaxis("商家A", [randrange(0, 100) for _ in range(6)]) .add_yaxis("商家B", [randrange(0, 100) for _ in range(6)]) .set_global_opts(title_opts=opts.TitleOpts(title="Bar-基本示例", subtitle="我是副标题")) .dump_options_with_quotes() ) return c def GeoMap() -> Geo: try: register_url("https://echarts-maps.github.io/echarts-countries-js/") except Exception: import ssl ssl._create_default_https_context = ssl._create_unverified_context register_url("https://echarts-maps.github.io/echarts-countries-js/") geo = ( Geo() .add_schema(maptype="瑞士") .set_global_opts(title_opts=opts.TitleOpts(title="瑞士")) .dump_options_with_quotes() # .render("geo_chart_countries_js.html") ) return geo
{"/weather_cralwer/weather_cralwer/spiders/today_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/db_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/init_db/init_city.py": ["/init_db/mysql_coon.py"], "/weather_cralwer/weather_cralwer/spiders/today_one_city_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/WeatherWeb/weather_show_app/drawviews.py": ["/WeatherWeb/weather_show_app/constant.py", "/WeatherWeb/weather_show_app/models.py"], "/WeatherWeb/weather_show_app/views.py": ["/WeatherWeb/weather_show_app/forms.py", "/WeatherWeb/weather_show_app/kmeans_process.py", "/WeatherWeb/weather_show_app/models.py"], "/init_db/fill_province.py": ["/init_db/mysql_coon.py"], "/init_db/fill_province_test.py": ["/init_db/fill_province.py"], "/weather_cralwer/weather_cralwer/pipelines.py": ["/weather_cralwer/weather_cralwer/items.py"]}
45,124
realzhengyiming/WeatherPlatform
refs/heads/main
/init_db/fill_province.py
# 用来填充 城市所属省份的 import json import pandas as pd import requests from init_db.mysql_coon import mysql_conn gaode = pd.read_excel("AMap_adcode_citycode_20210406.xlsx") def find_province_by_city_code(city_code): city_code = str(city_code) for index, row in gaode.iterrows(): name = row[0] code = row[1] if str(code) == city_code: return name return "" def get_province_by_gaode(address): response = requests.get( f'https://restapi.amap.com/v3/geocode/geo?address={address}&output=json&key=4719e1d3f1bb1a6c237cd0659e0265bc' ) dict_reponse = json.loads(response.text) province_name = "" if "geocodes" in dict_reponse: try: province_name = dict_reponse['geocodes'][0]['province'] except Exception as e: print(e) return province_name def get_location_by_gaode(address): response = requests.get( f'https://restapi.amap.com/v3/geocode/geo?address={address}&output=json&key=4719e1d3f1bb1a6c237cd0659e0265bc' ) dict_reponse = json.loads(response.text) lat_lng_location = "" if "geocodes" in dict_reponse: try: lat_lng_location = dict_reponse['geocodes'][0]['location'] except Exception as e: print(e) return lat_lng_location def fill_province_main(): cur = mysql_conn.cursor() # 这一段是填充省份的 select_city_name_sql = '''select name from City ;''' cur.execute(select_city_name_sql) citys = cur.fetchall() citys = [i[0] for i in citys] province_name = '' for city in citys: province_name = get_province_by_gaode(city) if not province_name: continue else: update_sql_pattern = '''update City set belong_province='{province_name}' where name = '{city}' '''.format( province_name=province_name, city=city ) cur.execute(update_sql_pattern) print(city) print(cur.fetchall()) mysql_conn.commit() print(province_name) print(citys) cur.close() print('创建数据库 py3_tstgr 成功!') def fill_lat_lng_location(): cur = mysql_conn.cursor() # 这一段是填充省份的 select_city_name_sql = '''select name from City ;''' cur.execute(select_city_name_sql) citys = cur.fetchall() citys = [i[0] for i in citys] location = '' for city in citys: location = get_location_by_gaode(city) if not location: continue else: update_sql_pattern = '''update City set location='{location}' where name = '{city}' '''.format( location=location, city=city ) cur.execute(update_sql_pattern) print(city) print(cur.fetchall()) mysql_conn.commit() print(location) print(citys) cur.close() print('创建数据库 py3_tstgr 成功!') if __name__ == '__main__': fill_lat_lng_location() # 填充location # 查找,插入
{"/weather_cralwer/weather_cralwer/spiders/today_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/db_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/init_db/init_city.py": ["/init_db/mysql_coon.py"], "/weather_cralwer/weather_cralwer/spiders/today_one_city_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/WeatherWeb/weather_show_app/drawviews.py": ["/WeatherWeb/weather_show_app/constant.py", "/WeatherWeb/weather_show_app/models.py"], "/WeatherWeb/weather_show_app/views.py": ["/WeatherWeb/weather_show_app/forms.py", "/WeatherWeb/weather_show_app/kmeans_process.py", "/WeatherWeb/weather_show_app/models.py"], "/init_db/fill_province.py": ["/init_db/mysql_coon.py"], "/init_db/fill_province_test.py": ["/init_db/fill_province.py"], "/weather_cralwer/weather_cralwer/pipelines.py": ["/weather_cralwer/weather_cralwer/items.py"]}
45,125
realzhengyiming/WeatherPlatform
refs/heads/main
/init_db/mysql_coon.py
import pymysql config = { "host": "127.0.0.1", # 地址 "port": 3306, # 端口 "user": "root", # 用户名 "password": "123456", # 密码 "database": "scrapy_django", # 数据库名;如果通过Python操作MySQL,要指定需要操作的数据库 "charset": "utf8mb4" } mysql_conn = pymysql.connect(**config)
{"/weather_cralwer/weather_cralwer/spiders/today_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/db_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/init_db/init_city.py": ["/init_db/mysql_coon.py"], "/weather_cralwer/weather_cralwer/spiders/today_one_city_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/WeatherWeb/weather_show_app/drawviews.py": ["/WeatherWeb/weather_show_app/constant.py", "/WeatherWeb/weather_show_app/models.py"], "/WeatherWeb/weather_show_app/views.py": ["/WeatherWeb/weather_show_app/forms.py", "/WeatherWeb/weather_show_app/kmeans_process.py", "/WeatherWeb/weather_show_app/models.py"], "/init_db/fill_province.py": ["/init_db/mysql_coon.py"], "/init_db/fill_province_test.py": ["/init_db/fill_province.py"], "/weather_cralwer/weather_cralwer/pipelines.py": ["/weather_cralwer/weather_cralwer/items.py"]}
45,126
realzhengyiming/WeatherPlatform
refs/heads/main
/WeatherWeb/analysis/constant/enums.py
# 这儿放各个api图表的
{"/weather_cralwer/weather_cralwer/spiders/today_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/db_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/init_db/init_city.py": ["/init_db/mysql_coon.py"], "/weather_cralwer/weather_cralwer/spiders/today_one_city_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/WeatherWeb/weather_show_app/drawviews.py": ["/WeatherWeb/weather_show_app/constant.py", "/WeatherWeb/weather_show_app/models.py"], "/WeatherWeb/weather_show_app/views.py": ["/WeatherWeb/weather_show_app/forms.py", "/WeatherWeb/weather_show_app/kmeans_process.py", "/WeatherWeb/weather_show_app/models.py"], "/init_db/fill_province.py": ["/init_db/mysql_coon.py"], "/init_db/fill_province_test.py": ["/init_db/fill_province.py"], "/weather_cralwer/weather_cralwer/pipelines.py": ["/weather_cralwer/weather_cralwer/items.py"]}
45,127
realzhengyiming/WeatherPlatform
refs/heads/main
/WeatherWeb/weather_show_app/urls.py
# -*- coding: utf-8 -*- from django.contrib.auth import views as auth_views from django.urls import path from weather_show_app import views, drawviews app_name = "weather_show_app" # 这儿需要设置这个来分辨不同的app urlpatterns = [ # todo 记得要删除这些坏东西/ path("index/", views.index, name="index"), path("", views.index, name='index'), path("loginpage/", views.loginPage, name="user_login"), path('logout/', views.userLogout, name="user_logout"), path("register/", views.register, name="user_register"), path("psssword-change/", auth_views.PasswordChangeView.as_view(template_name='weather_show_app/password_change_form.html', success_url='/index/'), name='password_change'), path('password-change-done/', auth_views.PasswordChangeDoneView.as_view( template_name="/registration/password-change-done.html"), name="password_change_done"), path("detail/", views.detailView, name="detail"), path("detaillist/", views.detaillist, name="detaillist"), path("today_weather/", views.today_weather_page, name="today_weather"), path("favourite/", views.favouriteHandler.as_view(), name="Favourite"), # 可视化的接口 path('bar/', drawviews.ChartView.as_view(), name='bar'), path("pie/", drawviews.PieView.as_view(), name="pie"), path('timeline/', drawviews.timeLineView.as_view(), name="timeline"), path("drawmap/", drawviews.drawMap.as_view(), name="drawMap"), path("get_today_aqi_line/", drawviews.get_today_aqi_bar.as_view(), name="get_today_aqi_line"), path("get_relative_humidity/", drawviews.get_today_average_humity.as_view(), name="draw_relative_humidity"), path("get_hostReplay/", drawviews.wind_graph.as_view(), name="get_hostReplay"), path("today_temperature_line/", drawviews.today_temperature_detail_line.as_view(), name="today_temperature_line"), # 这个改成了当踢的天气折线图 ]
{"/weather_cralwer/weather_cralwer/spiders/today_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/db_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/init_db/init_city.py": ["/init_db/mysql_coon.py"], "/weather_cralwer/weather_cralwer/spiders/today_one_city_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/WeatherWeb/weather_show_app/drawviews.py": ["/WeatherWeb/weather_show_app/constant.py", "/WeatherWeb/weather_show_app/models.py"], "/WeatherWeb/weather_show_app/views.py": ["/WeatherWeb/weather_show_app/forms.py", "/WeatherWeb/weather_show_app/kmeans_process.py", "/WeatherWeb/weather_show_app/models.py"], "/init_db/fill_province.py": ["/init_db/mysql_coon.py"], "/init_db/fill_province_test.py": ["/init_db/fill_province.py"], "/weather_cralwer/weather_cralwer/pipelines.py": ["/weather_cralwer/weather_cralwer/items.py"]}
45,128
realzhengyiming/WeatherPlatform
refs/heads/main
/WeatherWeb/weather_show_app/constant.py
# 出行指南 WALK_OUT_GUIDE_DICT = { '阴': "阴天,可能下雨,出行带伞", '雾': "出行请注意安全,保持距离", '小雨': '出行请带伞', '多云': '天气多云,适合外出', '晴': "天气晴朗,适合出行,出行请做好防晒", '中雨': '出行请带好伞', '雨夹雪': "出行注意安全,保湿距离", '大雨': "大雨视野受限,请减慢速度行驶", '小雪': '视情况而定,可以带伞', '阵雨': '出行请带伞', '雷阵雨': "出行请带伞", '中雪': "请带伞,并且注意行车速度", '大雪': "请带伞,并且注意行车速度", '暴雨': "请带伞,注意行车速度,不适宜出行", '阵雪': '视情况而定,可以带伞', '暴雪': "请带伞,注意行车速度,不适宜出行", '扬沙': "请带好口罩眼睛,加速慢性", '浮尘': "请带好口罩眼睛,加速慢性", '沙尘暴': "请带好口罩眼睛,加速慢性", '大暴雨': "不适合出行,建议雨停后出行" } # 穿衣指南 WEAR_GUIDE_DICT = { 30: '轻棉织物制作的短衣、短裙、薄短裙、短裤', 25: '棉麻面料的衬衫、薄长裙、薄T恤', 20: "套装、夹衣、风衣、休闲装、夹克衫、西装、薄毛衣", 15: "风衣、大衣、夹大衣、外套、毛衣、毛套装、西装、防寒服", 10: "棉衣、冬大衣、皮夹克、外罩大衣、厚毛衣、皮帽皮手套、皮袄", 5: '棉衣、冬大衣、皮夹克、厚呢外套、呢帽、手套、羽绒服、皮袄', 0: "棉衣、冬大衣、皮夹克、厚呢外套、呢帽、手套、羽绒服、裘皮大衣" } ALL_DIRECTION_MAPPING_DICT = { "北风": 0, "东北风": 1, "东风": 2, "东南风": 3, "南风": 4, "西南风": 5, "西风": 6, "西北风": 7 }
{"/weather_cralwer/weather_cralwer/spiders/today_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/db_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/init_db/init_city.py": ["/init_db/mysql_coon.py"], "/weather_cralwer/weather_cralwer/spiders/today_one_city_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/WeatherWeb/weather_show_app/drawviews.py": ["/WeatherWeb/weather_show_app/constant.py", "/WeatherWeb/weather_show_app/models.py"], "/WeatherWeb/weather_show_app/views.py": ["/WeatherWeb/weather_show_app/forms.py", "/WeatherWeb/weather_show_app/kmeans_process.py", "/WeatherWeb/weather_show_app/models.py"], "/init_db/fill_province.py": ["/init_db/mysql_coon.py"], "/init_db/fill_province_test.py": ["/init_db/fill_province.py"], "/weather_cralwer/weather_cralwer/pipelines.py": ["/weather_cralwer/weather_cralwer/items.py"]}
45,129
realzhengyiming/WeatherPlatform
refs/heads/main
/WeatherWeb/analysis/urls.py
from django.conf.urls import url from . import views, graph_api_view # 上面是api 的映射,下面是页面的url的映射,采用前后端分离的操作进行开发。 urlpatterns = [ url(r'^bar/$', graph_api_view.BarView.as_view(), name='demo'), url(r'^geo/$', graph_api_view.GeoView.as_view(), name="geo"), ] + [ url(r'^index/$', views.IndexView, name='demo'), ]
{"/weather_cralwer/weather_cralwer/spiders/today_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/db_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/init_db/init_city.py": ["/init_db/mysql_coon.py"], "/weather_cralwer/weather_cralwer/spiders/today_one_city_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/WeatherWeb/weather_show_app/drawviews.py": ["/WeatherWeb/weather_show_app/constant.py", "/WeatherWeb/weather_show_app/models.py"], "/WeatherWeb/weather_show_app/views.py": ["/WeatherWeb/weather_show_app/forms.py", "/WeatherWeb/weather_show_app/kmeans_process.py", "/WeatherWeb/weather_show_app/models.py"], "/init_db/fill_province.py": ["/init_db/mysql_coon.py"], "/init_db/fill_province_test.py": ["/init_db/fill_province.py"], "/weather_cralwer/weather_cralwer/pipelines.py": ["/weather_cralwer/weather_cralwer/items.py"]}
45,130
realzhengyiming/WeatherPlatform
refs/heads/main
/weather_cralwer/weather_cralwer/items.py
# Define here the models for your scraped items # # See documentation in: # https://docs.scrapy.org/en/latest/topics/items.html from scrapy import Item, Field from scrapy_djangoitem import DjangoItem from weather_show_app.models import DateWeather, HourWeather, Favourite, City class DateWeatherItem(DjangoItem): django_model = DateWeather city_name = Field() # 这个是临时增加的,用来存城市名字,后面再填充到model中去 extend_detail = Field() # 这个是json的东西 class HourWeatherItem(DjangoItem): django_model = HourWeather class FavouriteItem(DjangoItem): django_model = Favourite class CityItem(DjangoItem): django_model = City
{"/weather_cralwer/weather_cralwer/spiders/today_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/db_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/init_db/init_city.py": ["/init_db/mysql_coon.py"], "/weather_cralwer/weather_cralwer/spiders/today_one_city_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/WeatherWeb/weather_show_app/drawviews.py": ["/WeatherWeb/weather_show_app/constant.py", "/WeatherWeb/weather_show_app/models.py"], "/WeatherWeb/weather_show_app/views.py": ["/WeatherWeb/weather_show_app/forms.py", "/WeatherWeb/weather_show_app/kmeans_process.py", "/WeatherWeb/weather_show_app/models.py"], "/init_db/fill_province.py": ["/init_db/mysql_coon.py"], "/init_db/fill_province_test.py": ["/init_db/fill_province.py"], "/weather_cralwer/weather_cralwer/pipelines.py": ["/weather_cralwer/weather_cralwer/items.py"]}
45,131
realzhengyiming/WeatherPlatform
refs/heads/main
/WeatherWeb/weather_show_app/admin.py
from django.contrib import admin from weather_show_app.models import City from weather_show_app.models import DateWeather from weather_show_app.models import Favourite class ExtendCity(admin.ModelAdmin): search_fields = ("name", "pinyin", "code") # 搜索字段 list_display = ('id', 'name', 'pinyin', 'code',) class ExtendDateWeather(admin.ModelAdmin): search_fields = ("date",) # 搜索字段 list_display = ( "id", 'city', "state", "date", "max_temperature", "min_temperature", "update_date", "humidity", "wind_power", "wind_direction") def detail_weather(self, obj): # 好方便啊 num = len(obj.city.all()) return str(num) class ExtendFav(admin.ModelAdmin): list_display = ( "user", 'fav_city_number', ) def fav_city_number(self, obj): # 好方便啊 num = len(obj.city.all()) return str(num) def fav_city_list(self, obj): string = ";".join(obj.city.all()) return string admin.site.register(DateWeather, ExtendDateWeather) admin.site.register(City, ExtendCity) admin.site.register(Favourite, ExtendFav)
{"/weather_cralwer/weather_cralwer/spiders/today_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/db_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/init_db/init_city.py": ["/init_db/mysql_coon.py"], "/weather_cralwer/weather_cralwer/spiders/today_one_city_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/WeatherWeb/weather_show_app/drawviews.py": ["/WeatherWeb/weather_show_app/constant.py", "/WeatherWeb/weather_show_app/models.py"], "/WeatherWeb/weather_show_app/views.py": ["/WeatherWeb/weather_show_app/forms.py", "/WeatherWeb/weather_show_app/kmeans_process.py", "/WeatherWeb/weather_show_app/models.py"], "/init_db/fill_province.py": ["/init_db/mysql_coon.py"], "/init_db/fill_province_test.py": ["/init_db/fill_province.py"], "/weather_cralwer/weather_cralwer/pipelines.py": ["/weather_cralwer/weather_cralwer/items.py"]}
45,132
realzhengyiming/WeatherPlatform
refs/heads/main
/init_db/fill_province_test.py
from init_db.fill_province import get_province_by_gaode, get_location_by_gaode if __name__ == '__main__': # result = get_province_by_gaode("北京") # print(result) result = get_location_by_gaode("扬州") print(result)
{"/weather_cralwer/weather_cralwer/spiders/today_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/db_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/init_db/init_city.py": ["/init_db/mysql_coon.py"], "/weather_cralwer/weather_cralwer/spiders/today_one_city_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/WeatherWeb/weather_show_app/drawviews.py": ["/WeatherWeb/weather_show_app/constant.py", "/WeatherWeb/weather_show_app/models.py"], "/WeatherWeb/weather_show_app/views.py": ["/WeatherWeb/weather_show_app/forms.py", "/WeatherWeb/weather_show_app/kmeans_process.py", "/WeatherWeb/weather_show_app/models.py"], "/init_db/fill_province.py": ["/init_db/mysql_coon.py"], "/init_db/fill_province_test.py": ["/init_db/fill_province.py"], "/weather_cralwer/weather_cralwer/pipelines.py": ["/weather_cralwer/weather_cralwer/items.py"]}
45,133
realzhengyiming/WeatherPlatform
refs/heads/main
/WeatherWeb/weather_show_app/apps.py
from django.apps import AppConfig class WeatherShowAppConfig(AppConfig): name = 'weather_show_app'
{"/weather_cralwer/weather_cralwer/spiders/today_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/db_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/init_db/init_city.py": ["/init_db/mysql_coon.py"], "/weather_cralwer/weather_cralwer/spiders/today_one_city_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/WeatherWeb/weather_show_app/drawviews.py": ["/WeatherWeb/weather_show_app/constant.py", "/WeatherWeb/weather_show_app/models.py"], "/WeatherWeb/weather_show_app/views.py": ["/WeatherWeb/weather_show_app/forms.py", "/WeatherWeb/weather_show_app/kmeans_process.py", "/WeatherWeb/weather_show_app/models.py"], "/init_db/fill_province.py": ["/init_db/mysql_coon.py"], "/init_db/fill_province_test.py": ["/init_db/fill_province.py"], "/weather_cralwer/weather_cralwer/pipelines.py": ["/weather_cralwer/weather_cralwer/items.py"]}
45,134
realzhengyiming/WeatherPlatform
refs/heads/main
/weather_cralwer/weather_cralwer/pipelines.py
import django from weather_cralwer.weather_cralwer.items import DateWeather, DateWeatherItem from weather_show_app.models import City, HourWeather # 改成才可以,什么鬼》》。。 todo class DateWeatherPipeline: def insert_hour_weather(self, spider, item,weather): # check hour weather exist belong_to_date = item['belong_to_date'] hour = item['hour'] try: hour_weather = HourWeather.objects.filter(Weather=weather ,hour=hour, belong_to_date=belong_to_date) if len(hour_weather) == 0: # todo 这儿还是有问题的好 item.save(commit=True) spider.logger.info(f"保存成功:{item}") # hour_weather = hour_weather[0] # hour_weather.save(commit=True) else: spider.logger.info(f"{hour_weather}已经存在") except Exception as e: spider.logger.info(e) def update_date_weather(self, spider, item): date = item['date'] city_name = item['city_name'] # 查询到城市id city_result = City.objects.filter(name=city_name) if not city_result: spider.logger.error("不存在这个城市!") return item else: city = city_result[0] data_weather = DateWeather.objects.get(city=city.id, date=date) if 'dressing_index' in item.keys(): data_weather.dressing_index = item['dressing_index'] data_weather.save() def process_item(self, item, spider): if isinstance(item, DateWeatherItem): # 先保存多的数量的对象,然后在把多的数量的对象存进来保存少的对象 city_name = item["city_name"] date = item['date'] city_list = City.objects.filter(name=city_name) if not city_list: spider.logger.info(f"city {city_name} 找不到!") return item else: city = city_list[0] item["city"] = city city_id = city.id try: item.save(commit=True) # 保存后就有id了吗 except django.db.utils.IntegrityError: self.update_date_weather(spider, item) spider.logger.info(f"更新成功!{item}") if "extend_detail" in item.keys() and not not item['extend_detail']: # 如果有细节,把24小时细节补上 today_24hours_weather_list = item['extend_detail'] today_weather_object_list = DateWeather.objects.filter(date=date, city_id=city_id) if not today_weather_object_list: spider.logger.info(f"{city} {date} 的天气找不到!") return item else: today_weather = today_weather_object_list[0] for hour_weather in today_24hours_weather_list: hour_weather['Weather'] = today_weather self.insert_hour_weather(spider, hour_weather,today_weather) # if __name__ == '__main__': # any = {"name": "zhengyiming", "gender": "man"} # columns = ",".join([x for x in any.keys()]) # values = ",".join([f'"{x}"' for x in any.values()]) # sql = f"insert into test_table ({columns}) values ({values})" # print(sql)
{"/weather_cralwer/weather_cralwer/spiders/today_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/db_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/init_db/init_city.py": ["/init_db/mysql_coon.py"], "/weather_cralwer/weather_cralwer/spiders/today_one_city_weather_spider.py": ["/weather_cralwer/weather_cralwer/clean_util.py", "/weather_cralwer/weather_cralwer/items.py"], "/WeatherWeb/weather_show_app/drawviews.py": ["/WeatherWeb/weather_show_app/constant.py", "/WeatherWeb/weather_show_app/models.py"], "/WeatherWeb/weather_show_app/views.py": ["/WeatherWeb/weather_show_app/forms.py", "/WeatherWeb/weather_show_app/kmeans_process.py", "/WeatherWeb/weather_show_app/models.py"], "/init_db/fill_province.py": ["/init_db/mysql_coon.py"], "/init_db/fill_province_test.py": ["/init_db/fill_province.py"], "/weather_cralwer/weather_cralwer/pipelines.py": ["/weather_cralwer/weather_cralwer/items.py"]}
45,136
ergo/Python_RPG
refs/heads/master
/warriors.py
# Some heroes # A way to perform automatic fight sequence until one of heroes is dead # Heroes may want to have some very basic stats (health, agility, strength) and skills (dodge, block) # Heroes may want to be able to use some items that influence stats # Jakies cos from random import randint import sys print sys.version_info class Warrior(object): def __init__(self, name): self.name = name self.strength = 10 self.agility = 10 self.hp = 100 self.block = 10 self.dodge = 10 self.backpack = {"weapon": 4, "armor": 2, "boots": 5, "shield": 4} def recieve_damage(self, damage): damage = damage - self.backpack["armor"] if damage >= 0: self.hp -= damage def calculate_dmg(self): return self.strength + self.backpack["weapon"] def calculate_hit(self, dodge_value): return self.agility - dodge_value + randint(0, 75) def calculate_dodge(self): return self.dodge + self.backpack["boots"] def calculate_block(self): return self.block + self.backpack["shield"] @property def is_alive(self): return self.hp > 0 def __repr__(self): return '<Warrior name={}>'.format(self.name) ziutek = Warrior('wiran')
{"/Walka.py": ["/warriors.py"]}
45,137
ergo/Python_RPG
refs/heads/master
/Walka.py
# -*- coding: utf-8 -*- # Some heroes # A way to perform automatic fight sequence until one of heroes is dead # Heroes may want to have some very basic stats (health, agility, strength) and skills (dodge, block) # Heroes may want to be able to use some items that influence stats from warriors import Warrior from random import randint class Walka(object): def walka(self, attacker, defender): turn = 1 # licznik tur # walka, wymiana ciosów do smierci while attacker.is_alive and defender.is_alive: print("%s turn." % turn) attacker, defender = defender, attacker self.uderzenie(attacker, defender) turn += 1 if turn > 100: return def arena(self, attacker, defender): # funkcja glowna print ("Fight between %s and %s !" % (attacker.name, defender.name)) self.walka(attacker, defender) print ("Zwyciężca = %s !" % (self.wygrany(attacker, defender))) return True def uderzenie(self, attacker, defender): # atak wojownika attacker block = defender.calculate_block() # szansa na blok dodge = defender.calculate_dodge() # szansa na unik hit = attacker.calculate_hit(dodge) damage = attacker.calculate_dmg() if hit > dodge: if block > hit / 1.5: defender.recieve_damage(damage / 2) print("%s blocked the hit for half damage! ( %s hp)" % (defender.name, defender.hp)) else: defender.recieve_damage(damage) print ("%s got hit! ( %s hp)" % (defender.name, defender.hp)) else: print("%s dodged!" % defender.name) def wygrany(self, attacker, defender): # zwraca imie wygranego if attacker.hp > defender.hp: return attacker.name else: return defender.name fight_inst = Walka() fight_inst.arena(Warrior('a'), Warrior('b'))
{"/Walka.py": ["/warriors.py"]}
45,147
brian-mecha/hello-books
refs/heads/challenge_3
/api/books/views.py
from flask import jsonify, request from flask_jwt_extended import jwt_required, get_jwt_identity from api.models import Book, User, BorrowingHistory, datetime, timedelta from . import book from api.decorators import allow_pagination @book.route('/api/v2/books', methods=['GET']) @allow_pagination def get_all_books(): """ Function to return all books. :return: """ all_books = Book.get_all_books() if not all_books: return jsonify({"Message": "Library is empty."}), 204 else: response = [book.serialize for book in all_books] return jsonify(response), 200 @book.route('/api/v2/book/<int:book_id>', methods=['GET']) def get_book_by_id(book_id): """ Function to find a single book :param book_id: :return: """ data = Book.get_book(book_id) if not data: return {'Error': 'Book Does not Exist'}, 404 else: response = jsonify(data.serialize) response.status_code = 200 return response @book.route('/api/v2/users/book/<int:book_id>', methods=['POST']) @jwt_required def borrow_book(book_id): """ Function to borrow a book :param book_id: :return: """ book_is_present = Book.get_book(book_id) if not book_is_present: return {"Error": "Book does not exist"}, 403 available_books = Book.get_book_available_for_borrowing() book_is_available = [book for book in available_books if book.book_id == book_id] if not book_is_available: return {"Error": "This Book is not available for borrowing."}, 403 else: logged_user_email = get_jwt_identity() logged_user = User.get_user_by_email(logged_user_email) user_id = logged_user.id due_date = datetime.now() + timedelta(days=6) date_borrowed = datetime.now() BorrowingHistory(user_id=user_id, book_id=book_id, due_date=due_date, date_borrowed=date_borrowed, book_title=book_is_present.title, book_author=book_is_present.author, book_description=book_is_present.description).borrow_book() book = Book.get_book(book_id) book.availability = False book.create_book() return {"Success": "Book borrowed Successfully."}, 200 @book.route('/api/v2/users/book/<int:book_id>', methods=['PUT']) @jwt_required def return_book(book_id): """ Function to return a borrowed book :param book_id: :return: """ book = Book.get_book(book_id) if book is None: return {"message": "Book does not exist."}, 403 if book.availability is True: return {"message": "This book is not borrowed."}, 403 book.availability = True book.create_book() update = BorrowingHistory.get_book(book_id) update.returned = True update.returned_date = datetime.now() update.borrow_book() return {"message": "Book returned successfully."}, 200 @book.route('/api/v2/users/books', methods=['GET']) @jwt_required def user_borrowing_history(): unreturned = BorrowingHistory.unreturned_books_by_user() logged_user_email = get_jwt_identity() logged_user = User.get_user_by_email(logged_user_email) returned = request.args.get('returned') # get un-returned books if returned == 'false': if not unreturned: return jsonify({'Message': 'User does not have unreturned Books'}), 200 else: return jsonify([book.serialize for book in unreturned if book.user_id == logged_user.id]), 200 else: history = BorrowingHistory.user_borrowing_history() if history is None: return {"Message": "User doesn't have any borrowing history."}, 204 return jsonify([book.serialize for book in history if book.user_id == logged_user.id]), 200
{"/api/books/views.py": ["/api/models.py", "/api/books/__init__.py", "/api/decorators.py"], "/api/errors/handlers.py": ["/api/__init__.py"], "/api/users/views.py": ["/api/models.py"], "/tests/test_admin.py": ["/api/__init__.py"], "/tests/test_users.py": ["/api/__init__.py"], "/api/admin/views.py": ["/api/models.py", "/api/decorators.py"], "/api/decorators.py": ["/api/models.py"], "/tests/test_books.py": ["/api/__init__.py", "/tests/test_users.py", "/tests/test_admin.py"], "/api/__init__.py": ["/api/models.py", "/config.py", "/api/books/__init__.py"]}
45,148
brian-mecha/hello-books
refs/heads/challenge_3
/api/errors/handlers.py
from flask import jsonify from . import errors from api import jwt, RevokedTokens @errors.app_errorhandler(404) def error_404(e): return jsonify({"message": "The resource you are looking for " + "does not exist."}), 404 @errors.app_errorhandler(400) def error_400(e): return jsonify({"message": "Hello Books encountered an error while " + "processing your request. Kindly try again"}), 400 @errors.app_errorhandler(401) def error_401(e): return jsonify({"message": "The resource you are trying to access" + " requires more privileges."}), 401 @errors.app_errorhandler(500) def error_500(e): return jsonify({"message": "Hello Books was unable to process your " + "request. Kindly try again"}), 500 @errors.app_errorhandler(405) def error_500(e): return jsonify({"message": "The resource you are trying to access is not allowed for this requested URL."}), 500 @jwt.token_in_blacklist_loader def check_if_token_in_blacklist(decrypted_token): jti = decrypted_token['jti'] return RevokedTokens.is_jti_blacklisted(jti) @jwt.expired_token_loader def my_expired_token_callback(): return jsonify({ 'message': 'Your session has expired. Login again to continue.' }), 401 @jwt.revoked_token_loader def my_expired_token_callback(): return jsonify({ 'message': 'Your session has expired. Login again to continue.' }), 401
{"/api/books/views.py": ["/api/models.py", "/api/books/__init__.py", "/api/decorators.py"], "/api/errors/handlers.py": ["/api/__init__.py"], "/api/users/views.py": ["/api/models.py"], "/tests/test_admin.py": ["/api/__init__.py"], "/tests/test_users.py": ["/api/__init__.py"], "/api/admin/views.py": ["/api/models.py", "/api/decorators.py"], "/api/decorators.py": ["/api/models.py"], "/tests/test_books.py": ["/api/__init__.py", "/tests/test_users.py", "/tests/test_admin.py"], "/api/__init__.py": ["/api/models.py", "/config.py", "/api/books/__init__.py"]}
45,149
brian-mecha/hello-books
refs/heads/challenge_3
/config.py
import os class Config(object): """ General Config settings that are shared by all environments """ DEBUG = False TESTING = False ERROR_404_HELP = False # SQLALCHEMY_DATABASE_URI = 'postgresql://postgres:mozart@localhost:5432/hello_books' SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL') class TestingConfig(Config): """ Config setting for Testing """ TESTING = True DEBUG = True SQLALCHEMY_DATABASE_URI = os.getenv('SQLALCHEMY_DATABASE_URI') class DevelopmentConfig(Config): """ Config settings for Development """ DEBUG = True class ProductionConfig(Config): """ Config settings for Production """ DEBUG = False TESTING = False config_app = { 'development': DevelopmentConfig, 'production': ProductionConfig, 'testing': TestingConfig, 'default': ProductionConfig }
{"/api/books/views.py": ["/api/models.py", "/api/books/__init__.py", "/api/decorators.py"], "/api/errors/handlers.py": ["/api/__init__.py"], "/api/users/views.py": ["/api/models.py"], "/tests/test_admin.py": ["/api/__init__.py"], "/tests/test_users.py": ["/api/__init__.py"], "/api/admin/views.py": ["/api/models.py", "/api/decorators.py"], "/api/decorators.py": ["/api/models.py"], "/tests/test_books.py": ["/api/__init__.py", "/tests/test_users.py", "/tests/test_admin.py"], "/api/__init__.py": ["/api/models.py", "/config.py", "/api/books/__init__.py"]}
45,150
brian-mecha/hello-books
refs/heads/challenge_3
/api/users/views.py
import re from flask import jsonify, request from flask_jwt_extended import create_access_token, get_raw_jwt, get_jwt_identity, jwt_required from api.models import User, ActiveTokens, RevokedTokens, db, check_password_hash, generate_password_hash from . import user @user.route('/api/v2/auth/register', methods=['POST']) def register_user(): """ Registers a new user :return: """ password = request.data.get('password') username = request.data.get('username') email = request.data.get('email') is_admin = request.data.get('is_admin') if not password or password.isspace(): return jsonify({'message': 'Password Not Provided'}), 400 elif not username or username.isspace(): return jsonify({'message': 'Username Not Provided'}), 400 elif not email or email.isspace(): return jsonify({'message': 'Email Not Provided'}), 400 # elif is_admin is None: # return jsonify({'message': 'User role not provided'}), 403 users = User.all_users() users_username = [user for user in users if user.username == username] if users_username: return {"message": "This Username is already taken."}, 200 if len(password) < 8: return jsonify({'message': 'Password should be at least 8 characters long.'}), 400 if not re.match("(^(?=[a-zA-Z0-9#`~^@$?!%&,./']{8,}$)(?=.*?[a-z])(?=.*?[A-Z])(?=.*?[0-9]).*)", password): return jsonify({'message': 'Password should contain at ' 'least an uppercase character, lower case character and a number'}), 400 valid_email = re.match( "(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", email.strip()) if valid_email is None: return jsonify({'message': 'Please enter a valid Email!'}), 400 users_email = [user for user in users if user.email == email] if users_email: return {"message": "This Email already exists."}, 400 hashed_password = generate_password_hash(password=password) response = jsonify(User(username=username, user_password=hashed_password, email=email, is_admin=is_admin).create_user()) return {"message": "User registration successful."}, 201 @user.route('/api/v2/auth/login', methods=['POST']) def login_user(): """ Function to login user :return: """ user_data = request.get_json() if not user_data: return {"message": "Login credentials missing"}, 400 if user_data["email"] is None or user_data["email"].isspace(): return {"message": "Email is missing."}, 400 elif not user_data["password"] or user_data["password"].isspace(): return {"message": "Password is missing."}, 400 user = User.get_user_by_email(user_data["email"]) if not user: return jsonify({'message': 'User does not exist'}), 400 if user.is_administrator(): isAdmin = True else: isAdmin = False if not check_password_hash(user.user_password, user_data["password"]): return jsonify ({'message': "Wrong Email or Password"}), 400 access_token = create_access_token(identity=user_data["email"]) if access_token: response = {"message": "You logged in successfully.", "access_token": access_token, "isAdmin": isAdmin} return response, 200, {"access_token": access_token} else: return jsonify({'message': 'Wrong User Name or Password'}), 400 # if access_token: # try: # ActiveTokens(user_email=user_data["email"], access_token=access_token).create_active_token() # except: # return {"message": "User is already logged in."}, 200 # # response = {"message": "You logged in successfully.", "access_token": access_token} # # return response, 200, {"access_token": access_token} # else: # return jsonify({'message': 'Wrong User Name or Password'}), 400 @user.route('/api/v2/auth/logout', methods=['POST']) @jwt_required def logout_user(): """ Logs out the logged in user :return: """ user_email = request.json.get('email') if user_email is None: return {"Email is required to logout"}, 400 logged_in_user = get_jwt_identity() jti = get_raw_jwt()['jti'] if logged_in_user == user_email and not RevokedTokens.is_jti_blacklisted(jti): revoke_token = RevokedTokens(jti=jti) revoke_token.revoke_token() # ActiveTokens.find_user_with_token(user_email).delete_active_token() response = jsonify({'Success': 'User successfully logged out.'}) else: response = jsonify( {'Error': 'User with email: {} is not logged in or token has been blacklisted' .format(user_email)}) return response, 200 @user.route('/api/v2/auth/reset', methods=['POST']) @jwt_required def user_password_reset(): """ Method to reset user password :return: """ userdata = request.get_json() # try: if not userdata["email"] or userdata["email"].isspace(): return {"Error": "Email is missing."}, 400 elif not userdata["password"] or userdata["password"].isspace(): return {"Error": "Password is missing."}, 400 if len(userdata['password']) < 8: return jsonify({'message': 'Password should be at least 8 characters long.'}), 400 present_user = User.get_user_by_email(userdata["email"]) logged_in_user = User.get_user_by_email(get_jwt_identity()) if present_user != logged_in_user: return jsonify({'message': "Wrong email. " "Please use the email you logged in with."}), 400 else: new_password = generate_password_hash(password=userdata["password"]) if present_user.user_password == userdata["password"]: return jsonify({'message': "No changes detected in the password"}), 400 jti = get_raw_jwt()['jti'] revoke_token = RevokedTokens(jti=jti) revoke_token.revoke_token() # ActiveTokens.find_user_with_token(userdata["email"]).delete_active_token() present_user.user_password = new_password # present_user.set_password(password=userdata["password"]) present_user.create_user() # db.session.commit() return jsonify({"message": "Password reset successful."}), 200 # except: # return jsonify({"Error": "Password not Reset. Try again."}), 400
{"/api/books/views.py": ["/api/models.py", "/api/books/__init__.py", "/api/decorators.py"], "/api/errors/handlers.py": ["/api/__init__.py"], "/api/users/views.py": ["/api/models.py"], "/tests/test_admin.py": ["/api/__init__.py"], "/tests/test_users.py": ["/api/__init__.py"], "/api/admin/views.py": ["/api/models.py", "/api/decorators.py"], "/api/decorators.py": ["/api/models.py"], "/tests/test_books.py": ["/api/__init__.py", "/tests/test_users.py", "/tests/test_admin.py"], "/api/__init__.py": ["/api/models.py", "/config.py", "/api/books/__init__.py"]}
45,151
brian-mecha/hello-books
refs/heads/challenge_3
/tests/test_admin.py
import unittest import json from api import create_app, db class AdminTestCase(unittest.TestCase): """ Tests for all the admin user checkpoints """ def setUp(self): """ Defines the test variables and initializes the Book api :return: """ self.app = create_app(config_name="testing") self.client = self.app.test_client() self.admin = { 'email': 'brainAdmin@gmail.com', 'username': 'brianAdmin', 'password': 'r7eee#eooM', 'is_admin': True } self.book = { 'title': 'Kamusi ya Methali', 'description': 'A collection of swahili sayings', 'author': 'Brian Mecha', 'availability': True } with self.app.app_context(): db.create_all() # self.book = book.serialize() def register_login_admin(self): # Register a new admin self.client.post('/api/v2/auth/register', data=json.dumps(self.admin), headers={'content-type': 'application/json'}) # Login a admin login_response = self.client.post( '/api/v2/auth/login', data=json.dumps(self.admin), headers={'content-type': 'application/json'}) # Get admin access token access_token = json.loads(login_response.data.decode('utf-8'))['access_token'] return access_token def test_add_book(self): """ Tests whether a book can be added :return: """ # Test to add book without access token response = self.client.post('/api/v2/books', data=json.dumps(self.book), content_type="application/json") self.assertEqual(response.status_code, 401) self.assertIn('Missing Authorization Header', str(response.data)) # Test to add book with admin access token access_token = self.register_login_admin() # Add a new book with an admin access token response = self.client.post( '/api/v2/books', data=json.dumps(self.book), headers={'content-type': 'application/json', 'Authorization': 'Bearer {}'.format(access_token)}) self.assertEqual(response.status_code, 201) self.assertIn('Book added successfully.', str(response.data)) # Add a book that already exist response = self.client.post( '/api/v2/books', data=json.dumps(self.book), headers={'content-type': 'application/json', 'Authorization': 'Bearer {}'.format(access_token)}) # Test if the same book can be added again self.assertIn('Book with that title already exists.', str(response.data)) def test_add_book_without_title(self): """ Tests whether a book can be added without a title :return: """ access_token = self.register_login_admin() book = {"title": "", "description": "What a wonderful bootcamp", "author": "Mecha B", "availability": True} response = self.client.post('/api/v2/books', data=json.dumps(book), headers={'content-type': 'application/json', 'Authorization': 'Bearer {}'.format(access_token)}) self.assertEqual(response.status_code, 403) self.assertIn('Book must have a Title', str(response.data)) def test_add_book_without_description(self): """ Tests whether a book can be added without a description :return: """ access_token = self.register_login_admin() book = {"title": "COHORT 26", "description": " ", "author": "Mecha B", "availability": True} response = self.client.post('/api/v2/books', data=json.dumps(book), headers={'content-type': 'application/json', 'Authorization': 'Bearer {}'.format(access_token)}) self.assertEqual(response.status_code, 403) self.assertIn('Book must have a Description', str(response.data)) def test_add_book_without_author(self): """ Tests whether a book can be added without a author :return: """ access_token = self.register_login_admin() book = {"title": "COHORT 26", "description": "Wonderful scenery", "author": " ", "availability": True} response = self.client.post('/api/v2/books', data=json.dumps(book), headers={'content-type': 'application/json', 'Authorization': 'Bearer {}'.format(access_token)}) self.assertEqual(response.status_code, 403) self.assertIn('Book must have an Author', str(response.data)) def test_update_book(self): """ Tests whether a book can be updated :return: """ access_token = self.register_login_admin() self.client.post( '/api/v2/books', data=json.dumps(self.book), headers={'content-type': 'application/json', 'Authorization': 'Bearer {}'.format(access_token)}) book = {"title": "BOOTCAMP26", "description": "Wonderful", "author": "Thosekuys", "availability": True} response = self.client.put('/api/v2/book/1', data=json.dumps(book), headers={'content-type': 'application/json', 'Authorization': 'Bearer {}'.format(access_token)} ) self.assertEqual(response.status_code, 200) book = {"title": "", "description": "Wonderful", "author": "Thosekuys", "availability": True} response = self.client.put('/api/v2/book/1', data=json.dumps(book), headers={'content-type': 'application/json', 'Authorization': 'Bearer {}'.format(access_token)} ) self.assertEqual(response.status_code, 403) self.assertIn('Book must have a Title', str(response.data)) book = {"title": "Book","description": " ", "author": "Thosekuys", "availability": True} response = self.client.put('/api/v2/book/1', data=json.dumps(book), headers={'content-type': 'application/json', 'Authorization': 'Bearer {}'.format(access_token)} ) self.assertEqual(response.status_code, 403) self.assertIn('Book must have a Description', str(response.data)) book = {"title": "Book","description": "Describe", "author": "", "availability": True} response = self.client.put('/api/v2/book/1', data=json.dumps(book), headers={'content-type': 'application/json', 'Authorization': 'Bearer {}'.format(access_token)} ) self.assertEqual(response.status_code, 403) self.assertIn('Book must have an Author', str(response.data)) book = {"title": "Book","description": "Describe", "author": "Brian", "availability": ""} response = self.client.put('/api/v2/book/1', data=json.dumps(book), headers={'content-type': 'application/json', 'Authorization': 'Bearer {}'.format(access_token)} ) self.assertEqual(response.status_code, 400) def test_delete_book(self): """ Tests whether a book can be updated :return: """ access_token = self.register_login_admin() self.client.post('/api/v2/books', data=json.dumps(self.book), headers={'content-type': 'application/json', 'Authorization': 'Bearer {}'.format(access_token)}) response = self.client.delete('/api/v2/book/1', data=json.dumps(self.book), headers={'content-type': 'application/json', 'Authorization': 'Bearer {}'.format(access_token)} ) self.assertEqual(response.status_code, 200) self.assertIn('Book deleted successfully.', str(response.data)) response = self.client.delete('/api/v2/book/2', data=json.dumps(self.book), headers={'content-type': 'application/json', 'Authorization': 'Bearer {}'.format(access_token)} ) self.assertEqual(response.status_code, 404) self.assertIn('Book Does not Exist', str(response.data)) def tearDown(self): """ Drop all tables after tests are complete. :return: """ with self.app.app_context(): db.session.remove() db.drop_all() if __name__ == '__main__': unittest.main()
{"/api/books/views.py": ["/api/models.py", "/api/books/__init__.py", "/api/decorators.py"], "/api/errors/handlers.py": ["/api/__init__.py"], "/api/users/views.py": ["/api/models.py"], "/tests/test_admin.py": ["/api/__init__.py"], "/tests/test_users.py": ["/api/__init__.py"], "/api/admin/views.py": ["/api/models.py", "/api/decorators.py"], "/api/decorators.py": ["/api/models.py"], "/tests/test_books.py": ["/api/__init__.py", "/tests/test_users.py", "/tests/test_admin.py"], "/api/__init__.py": ["/api/models.py", "/config.py", "/api/books/__init__.py"]}
45,152
brian-mecha/hello-books
refs/heads/challenge_3
/tests/test_users.py
import unittest import json from api import create_app, db class UserTestCase(unittest.TestCase): """ Tests for all the user API endpoints """ def setUp(self): """ Defines the test variables and initializes the User api :return: """ self.app = create_app(config_name="testing") self.client = self.app.test_client() self.user = {'email': 'brain@gmail.com', 'username': 'brian', 'password': 'r7eeeeooM', 'is_admin': False } # Set app to the current context with self.app.app_context(): db.drop_all() db.create_all() def register_login_user(self): # Register and login a new admin reg = self.client.post('/api/v2/auth/register', data=json.dumps(self.user), headers={'content-type': 'application/json'}) # Login a admin login_response = self.client.post( '/api/v2/auth/login', data=json.dumps(self.user), headers={'content-type': 'application/json'}) # Get admin access token access_token = json.loads(login_response.data.decode('utf-8'))['access_token'] return access_token def test_sanity(self): """Sanity check""" self.assertEqual(1, 1) def test_user_registration(self): """ Test :param self: :return: """ response = self.client.post('/api/v2/auth/register', data=json.dumps(self.user), content_type='application/json') self.assertEqual(response.status_code, 201) def test_user_registration_duplicate(self): """ Tests for duplicate user registration :return: """ self.client.post('/api/v2/auth/register', data=json.dumps(self.user), content_type='application/json') response = self.client.post('/api/v2/auth/register', data=json.dumps(self.user), content_type='application/json') self.assertEqual(response.status_code, 200) self.assertIn("This Email already exists.", str(response.data)) def test_register_user_without_email(self): """ Tests whether the register user registration API endpoint can pass without email :return: """ user = {"username": "sddsdd", "password": "yryrur8d"} response = self.client.post('/api/v2/auth/register', data=json.dumps(user), content_type="application/json") self.assertEqual(response.status_code, 403) self.assertIn("Email Not Provided", str(response.data)) def test_register_user_without_role(self): """ Tests whether the register user registration API endpoint can pass without role :return: """ user = {"username": "sddsdd", "password": "r7eeeeooM", "email": "b@gmail.com"} response = self.client.post('/api/v2/auth/register', data=json.dumps(user), content_type="application/json") self.assertEqual(response.status_code, 403) self.assertIn("User role not provided", str(response.data)) def test_register_user_with_invalid_email_format(self): """ Tests whether the register user registration API endpoint can pass with invalid email format :return: """ user = {"username": "sddsdd", "password": "r7eeeeooM", "email": "bg", "is_admin": False} response = self.client.post('/api/v2/auth/register', data=json.dumps(user), content_type="application/json") self.assertEqual(response.status_code, 403) self.assertIn("Please enter a valid Email!", str(response.data)) def test_register_user_without_username(self): """ Tests whether the register user registration API endpoint can pass without a Username :return: """ user = {"username": "", "password": "yryrur8d"} response = self.client.post('/api/v2/auth/register', data=json.dumps(user), content_type="application/json") self.assertEqual(response.status_code, 403) self.assertIn("Username Not Provided", str(response.data)) def test_register_user_without_password(self): """ Tests whether the register user registration API endpoint can pass without a Password :return: """ user = {"username": "Brian", "password": "", "email": "b@gmail.com", "is_admin": False} response = self.client.post('/api/v2/auth/register', data=json.dumps(user), content_type="application/json") self.assertEqual(response.status_code, 403) self.assertIn("Password Not Provided", str(response.data)) def user_login(self): """ Tests whether a user can login :return: """ # Login a user response = self.client.post( '/api/v2/auth/login', data=json.dumps(self.user), headers={'content-type': 'application/json'}) self.assertEqual(response.status_code, 200) self.assertIn('Successfully login', str(response.data), msg="Login successful") self.assertIn('access_token', str(response.data), msg="Access token issued") def test_unregistered_user_login(self): """ Tests whether a user can login :return: """ user = {"email": "not@gmail.com", "password": "wsed"} response = self.client.post('/api/v2/auth/login', data=json.dumps(user), content_type="application/json") self.assertEqual(response.status_code, 403) self.assertIn("User does not exist", str(response.data)) def test_unregistered_user_logout(self): """ Tests whether a user can login :return: """ user = {'email': 'brainyu@gmail.com', 'username': 'brianu', 'password': '111111', 'is_admin': False } response = self.client.post('/api/v2/auth/logout', data=json.dumps(user), content_type="application/json") self.assertEqual(response.status_code, 401) self.assertIn("Missing Authorization Header", str(response.data)) def test_login_no_email(self): """ Tests Login API endpoint when email is not provided """ user = {"email": "", "password": "yuyyuuuu"} response = self.client.post('/api/v2/auth/login', data=json.dumps(user), content_type="application/json") self.assertEqual(response.status_code, 403) self.assertIn("User does not exist", str(response.data)) def test_login_no_password(self): """ Tests Login API endpoint when password is not provided """ user = {"email": "mecha@gmail.com", "password": ""} response = self.client.post('/api/v2/auth/login', data=json.dumps(user), content_type="application/json") self.assertEqual(response.status_code, 401) self.assertIn("Password is missing.", str(response.data)) def test_user_logout(self): access_token = self.register_login_user() response = self.client.post('/api/v2/auth/logout', headers={'content-type': 'application/json', 'Authorization': 'Bearer {}'.format(access_token)}) self.assertEqual(response.status_code, 400) def test_user_reset_password(self): access_token = self.register_login_user() user = {"email": "brain@gmail.com", "password": "yutuuruty891!"} response = self.client.post('/api/v2/auth/reset', data=json.dumps(user), headers={'content-type': 'application/json', 'Authorization': 'Bearer {}'.format(access_token)}) self.assertEqual(response.status_code, 200) self.assertIn("Password reset successful.", str(response.data)) def tearDown(self): """ Drop all tables after tests are complete. :return: """ with self.app.app_context(): db.session.remove() db.drop_all() if __name__ == '__main__': unittest.main()
{"/api/books/views.py": ["/api/models.py", "/api/books/__init__.py", "/api/decorators.py"], "/api/errors/handlers.py": ["/api/__init__.py"], "/api/users/views.py": ["/api/models.py"], "/tests/test_admin.py": ["/api/__init__.py"], "/tests/test_users.py": ["/api/__init__.py"], "/api/admin/views.py": ["/api/models.py", "/api/decorators.py"], "/api/decorators.py": ["/api/models.py"], "/tests/test_books.py": ["/api/__init__.py", "/tests/test_users.py", "/tests/test_admin.py"], "/api/__init__.py": ["/api/models.py", "/config.py", "/api/books/__init__.py"]}
45,153
brian-mecha/hello-books
refs/heads/challenge_3
/api/books/__init__.py
from flask import Blueprint book = Blueprint('books', __name__) from . import views
{"/api/books/views.py": ["/api/models.py", "/api/books/__init__.py", "/api/decorators.py"], "/api/errors/handlers.py": ["/api/__init__.py"], "/api/users/views.py": ["/api/models.py"], "/tests/test_admin.py": ["/api/__init__.py"], "/tests/test_users.py": ["/api/__init__.py"], "/api/admin/views.py": ["/api/models.py", "/api/decorators.py"], "/api/decorators.py": ["/api/models.py"], "/tests/test_books.py": ["/api/__init__.py", "/tests/test_users.py", "/tests/test_admin.py"], "/api/__init__.py": ["/api/models.py", "/config.py", "/api/books/__init__.py"]}
45,154
brian-mecha/hello-books
refs/heads/challenge_3
/api/admin/views.py
from flask import jsonify, request from jsonschema import validate from flask_jwt_extended import get_raw_jwt, get_jwt_identity, jwt_required from api.models import User, Book, RevokedTokens from . import admin from api.models import db from api.decorators import admin_user # def verify_token_and_if_user_is_admin(): # jti = get_raw_jwt()['jti'] # logged_email = get_jwt_identity() # logged_user = User.get_user_by_email(logged_email) # # if RevokedTokens.is_jti_blacklisted(jti): # return jsonify({'message': 'This User token has been blacklisted'}), 401 # if not logged_user.is_admin: # return jsonify({'message': 'You are not authorized to access this URL.'}), 401 @admin.route('/api/v2/books', methods=['POST']) @jwt_required @admin_user def create_book(): """ Function to add a book :return: """ title = request.data.get('title') description = request.data.get('description') author = request.data.get('author') availability = request.data.get('availability') if not title or title.isspace(): return jsonify({ 'message': 'Book must have a Title' }), 400 if not description or description.isspace(): return jsonify({ 'message': 'Book must have a Description' }), 400 if not author or author.isspace(): return jsonify({ 'message': 'Book must have an Author' }), 400 # if availability is None: # return jsonify({ # 'message': 'Book must have an availability status' # }), 400 books = Book.all_books() present = [book for book in books if book.title == title] if present: return {'message': 'Book with that title already exists.'}, 400 else: new_book = Book(title=title, description=description, availability=availability, author=author) new_book.create_book() return jsonify({'message': 'Book added successfully.'}), 201 @admin.route('/api/v2/book/<int:book_id>', methods=['DELETE']) @jwt_required @admin_user def delete_book(book_id): """Function to delete a book""" data = Book.get_book(book_id) if not data: return {'Error': 'Book Does not Exist'}, 404 if data: data.deleted = True db.session.commit() return jsonify({'message': 'Book deleted successfully.'}), 200 else: return {'Error': 'Book Does not Exist'}, 404 @admin.route('/api/v2/book/<int:book_id>', methods=['PUT']) @jwt_required @admin_user def edit_put(book_id): """ Function to update a book :param book_id: :return: """ data = request.get_json() try: schema = { "type": "object", "properties": { "title": {"type": "string"}, "description": {"type": "string"}, "author": {"type": "string"}, # "availability": {"type": "boolean"} }, "required": ["description", "title", "author"] } validate(data, schema) except: return {"message": "Missing or wrong inputs"}, 400 book_find = Book.get_book(book_id) if not book_find: return {'message': 'Book Does not Exist'}, 404 if data is None: response = jsonify({"message": "No Book Update Information Passed"}) response.status_code = 400 return response if not data["title"] or data["title"].isspace(): return {'message': 'Book must have a Title'}, 403 elif data["description"].isspace() or not data["description"]: return {'message': 'Book must have a Description'}, 403 elif not data["author"] or data["author"].isspace(): return {'message': 'Book must have an Author'}, 403 # elif not data["availability"]: # return {'Error': 'Book status is not provided.'}, 403 if book_find: book_find.title = data["title"] book_find.description = data["description"] book_find.author = data["author"] # book_find.availability = data["availability"] db.session.commit() return jsonify({'message': 'Book updated successfully.'}), 200
{"/api/books/views.py": ["/api/models.py", "/api/books/__init__.py", "/api/decorators.py"], "/api/errors/handlers.py": ["/api/__init__.py"], "/api/users/views.py": ["/api/models.py"], "/tests/test_admin.py": ["/api/__init__.py"], "/tests/test_users.py": ["/api/__init__.py"], "/api/admin/views.py": ["/api/models.py", "/api/decorators.py"], "/api/decorators.py": ["/api/models.py"], "/tests/test_books.py": ["/api/__init__.py", "/tests/test_users.py", "/tests/test_admin.py"], "/api/__init__.py": ["/api/models.py", "/config.py", "/api/books/__init__.py"]}
45,155
brian-mecha/hello-books
refs/heads/challenge_3
/api/decorators.py
import json from functools import wraps from flask import request, jsonify from .models import get_paginated, User from flask_jwt_extended import get_jwt_identity def allow_pagination(func): """ Decorator for paginating results :param func: :return: """ @wraps(func) def paginate(*args, **kwargs): limit = request.args.get('limit') page = 1 if not request.args.get('page') else request.args.get('page') rv = func(*args, **kwargs)[0] results = json.loads(rv.data) if limit: paginated = get_paginated(limit, results, request.path, page) if not paginated: return jsonify(message='The requested page was not found'), 404 return jsonify(paginated), 200 return func(*args, **kwargs) return paginate def admin_user(func): """ Decorator for protecting admin-only endpoints :param func: :return: """ @wraps(func) def check_admin_status(*args, **kwargs): current_user_email = get_jwt_identity() user = User.get_user_by_email(current_user_email) if not user.is_admin: return jsonify(message='You are not authorized to access this resource.'), 401 return func(*args, **kwargs) return check_admin_status
{"/api/books/views.py": ["/api/models.py", "/api/books/__init__.py", "/api/decorators.py"], "/api/errors/handlers.py": ["/api/__init__.py"], "/api/users/views.py": ["/api/models.py"], "/tests/test_admin.py": ["/api/__init__.py"], "/tests/test_users.py": ["/api/__init__.py"], "/api/admin/views.py": ["/api/models.py", "/api/decorators.py"], "/api/decorators.py": ["/api/models.py"], "/tests/test_books.py": ["/api/__init__.py", "/tests/test_users.py", "/tests/test_admin.py"], "/api/__init__.py": ["/api/models.py", "/config.py", "/api/books/__init__.py"]}
45,156
brian-mecha/hello-books
refs/heads/challenge_3
/api/models.py
""" Contains models used in our apps. """ from werkzeug.security import check_password_hash, generate_password_hash from datetime import datetime, timedelta from flask_sqlalchemy import SQLAlchemy from math import ceil from sqlalchemy import desc # Initializes Database db = SQLAlchemy() class User(db.Model): """ Class containing the User model """ __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True, autoincrement=True) email = db.Column(db.String(60), index=True, unique=True) username = db.Column(db.String(60), index=True, unique=True) user_password = db.Column(db.String(128)) is_admin = db.Column(db.Boolean, default=False) created_at = db.Column(db.Date, default=db.func.current_timestamp()) def __init__(self, username, user_password, email, is_admin): self.username = username self.email = email self.user_password = user_password self.is_admin = is_admin @staticmethod def set_password(password): """ Hashes the password :param password: :return: """ return str(generate_password_hash(password)) @staticmethod def check_password(password, hashed_password): """ Checks whether hashed password matches the actual password :param password: :return: """ # user_password = str(generate_password_hash(password)) # return check_password_hash(user_password, password) return check_password_hash(hashed_password, password) def is_administrator(self): return self.is_admin is True def create_user(self): db.session.add(self) db.session.commit() @staticmethod def all_users(): return User.query.all() @staticmethod def get_user_by_id(user_id): return User.query.filter_by(id=user_id).first() @staticmethod def get_user_by_email(email): return User.query.filter_by(email=email).first() def __repr__(self): return '<User: {}'.format(self.username) class Book(db.Model): """ Class containing the Books model. """ __tablename__ = 'books' book_id = db.Column(db.Integer, primary_key=True, autoincrement=True) title = db.Column(db.String(60), nullable=False, unique=True) author = db.Column(db.String(60), nullable=False) description = db.Column(db.Text(), nullable=False) availability = db.Column(db.Boolean, default=True) created_at = db.Column(db.Date, nullable=False, default=datetime.today()) deleted = db.Column(db.Boolean(), default=False) def create_book(self): db.session.add(self) db.session.commit() def delete_book(self): db.session.delete(self) db.session.commit() @staticmethod def get_book(book_id): return Book.query.filter_by(book_id=book_id).first() @staticmethod def get_all_books(): return Book.query.filter_by(deleted=False).order_by(desc(Book.created_at)) @staticmethod def all_books(): return Book.query.all() @staticmethod def get_book_available_for_borrowing(): return Book.query.filter_by(availability=True).all() def __repr__(self): return '<Book: {}>'.format(self.book_id) @property def serialize(self): """Serialize.""" return { 'book_id': self.book_id, 'title': self.title, 'author': self.author, 'description': self.description, 'availability': self.availability } class BorrowingHistory(db.Model): """ Class contains the borrowing history """ __tablename__ = 'borrowed_books' id = db.Column(db.Integer, primary_key=True, autoincrement=True) book_id = db.Column(db.Integer, db.ForeignKey('books.book_id'), nullable=False, default=1) book_title = db.Column(db.String(60), nullable=False) book_author = db.Column(db.String(60), nullable=False) book_description = db.Column(db.Text(), nullable=False) user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False, default=1) date_borrowed = db.Column(db.Date, nullable=False, default=datetime.now()) due_date = db.Column(db.Date, nullable=False, default=datetime.today()) returned = db.Column(db.Boolean, default=False) returned_date = db.Column(db.DateTime, default=datetime.today()) @staticmethod def user_borrowing_history(): hist = BorrowingHistory.query.all() return hist @staticmethod def unreturned_books_by_user(): return BorrowingHistory.query.filter_by(returned=False).all() def borrow_book(self): db.session.add(self) db.session.commit() def __repr__(self): return '<Borrowing History: {}>'.format(self.book_id) @staticmethod def get_book(book_id): return BorrowingHistory.query.filter_by(book_id=book_id, returned=False).first() @property def serialize(self): """Serialize.""" return { 'book_id': self.book_id, 'book_title': self.book_title, 'book_author': self.book_author, 'book_description': self.book_description, 'user_id': self.user_id, 'date_borrowed': self.date_borrowed, 'due_date': self.due_date, 'returned': self.returned, 'returned_date': self.returned_date } class ActiveTokens(db.Model): """ Class containing the active tokens """ __tablename__ = 'active_tokens' id = db.Column(db.Integer, primary_key=True) time_created = db.Column(db.DateTime, default=datetime.today()) user_email = db.Column(db.String, unique=True) access_token = db.Column(db.String, unique=True) def __init__(self, user_email, access_token): self.user_email = user_email self.access_token = access_token def create_active_token(self): db.session.add(self) db.session.commit() def delete_active_token(self): db.session.delete(self) db.session.commit() def token_is_expired(self): return (datetime.now() - self.time_created) > timedelta(minutes=60) @staticmethod def find_user_with_token(user_email): return ActiveTokens.query.filter_by(user_email=user_email).first() class RevokedTokens(db.Model): """ Class containing revoked tokens """ __tablename__ = 'revoked_tokens' id = db.Column(db.Integer, primary_key=True) time_revoked = db.Column(db.DateTime, default=datetime.today()) jti = db.Column(db.String(200), unique=True) def revoke_token(self): db.session.add(self) db.session.commit() @staticmethod def is_jti_blacklisted(jti): if RevokedTokens.query.filter_by(jti=jti).first(): return True return False def group(list_obj, group_len): """ Group objects in a list into lists with length group_len :param list_obj: :param group_len: :return: """ for i in range(0, len(list_obj), group_len): yield list_obj[i:i+group_len] def get_paginated(limit_param, results, url, page_param): """ Return paginated results :param limit_param: :param results: :param url: :param page_param: :return: """ page = int(page_param) limit = int(limit_param) page_count = ceil(len(results) / limit) paginated = {} if page == 1: paginated['previous'] = 'None' else: paginated['previous'] = url + '?page={}&limit={}'.format(page - 1, limit) if page < page_count: paginated['next'] = url + '?page={}&limit={}'.format(page + 1, limit) elif page > page_count: return False else: paginated['next'] = 'None' for i, value in enumerate(group(results, limit)): if i == (page - 1): paginated['results'] = value break return paginated
{"/api/books/views.py": ["/api/models.py", "/api/books/__init__.py", "/api/decorators.py"], "/api/errors/handlers.py": ["/api/__init__.py"], "/api/users/views.py": ["/api/models.py"], "/tests/test_admin.py": ["/api/__init__.py"], "/tests/test_users.py": ["/api/__init__.py"], "/api/admin/views.py": ["/api/models.py", "/api/decorators.py"], "/api/decorators.py": ["/api/models.py"], "/tests/test_books.py": ["/api/__init__.py", "/tests/test_users.py", "/tests/test_admin.py"], "/api/__init__.py": ["/api/models.py", "/config.py", "/api/books/__init__.py"]}
45,157
brian-mecha/hello-books
refs/heads/challenge_3
/tests/test_books.py
import unittest import json from api import create_app, db from tests.test_users import UserTestCase from tests.test_admin import AdminTestCase class BookTestCase(unittest.TestCase): """ Tests for all the books endpoints """ def setUp(self): """ Defines the test variables and initializes the Book api :return: """ self.app = create_app(config_name="testing") self.client = self.app.test_client() self.user = { 'email': 'brain@gmail.com', 'username': 'brian', 'password': 'r7eee#eooM', 'is_admin': False } self.admin = { 'email': 'brainAdmin@gmail.com', 'username': 'brianAdmin', 'password': 'r7eee#eooM', 'is_admin': True } self.book = { 'title': 'Kamusi ya Methali', 'description': 'A collection of swahili sayings', 'author': 'Brian Mecha', 'availability': True } with self.app.app_context(): db.create_all() # def test_books(self): # """ # Tests to get all books # :return: # """ # response = self.client.get('/api/v2/books', content_type="application/json") # self.assertEqual(response.status_code, 204) def test_get_a_single_book(self): """ Tests whether you can retrieve a single book. :return: """ response = self.client.get('/api/v2/book/1', content_type="application/json") self.assertEqual(response.status_code, 404) self.assertIn("Book Does not Exist", str(response.data)) def test_borrow_book(self): """ Tests whether a logged in user can borrow a book :return: """ access_token = UserTestCase.register_login_user(self) # Test to borrow a non-existent book response = self.client.post('/api/v2/users/book/1', headers={'content-type': 'application/json', 'Authorization': 'Bearer {}'.format(access_token)}) self.assertEqual(response.status_code, 403) self.assertIn("Book does not exist", str(response.data)) def test_borrow_book_with_token(self): admin_access_token = AdminTestCase.register_login_admin(self) access_token = UserTestCase.register_login_user(self) # Admin user adds a book response = self.client.post('/api/v2/books', data=json.dumps(self.book), headers={'content-type': 'application/json', 'Authorization': 'Bearer {}'.format(admin_access_token)}) self.assertEqual(response.status_code, 201) self.assertIn('Book added successfully.', str(response.data)) # Test to test whether a logged in user can borrow a book response = self.client.post('/api/v2/users/book/1', data=json.dumps(self.book), headers={'content-type': 'application/json', 'Authorization': 'Bearer {}'.format(access_token)}) self.assertEqual(response.status_code, 200) self.assertIn("Book borrowed Successfully.", str(response.data)) # Test whether a book can be borrowed twice response = self.client.post('/api/v2/users/book/1', data=json.dumps(self.book), headers={'content-type': 'application/json', 'Authorization': 'Bearer {}'.format(access_token)}) self.assertEqual(response.status_code, 403) self.assertIn("This Book is not available for borrowing.", str(response.data)) # Test to test whether a logged in user can return a borrowed book response = self.client.put('/api/v2/users/book/1', data=json.dumps(self.book), headers={'content-type': 'application/json', 'Authorization': 'Bearer {}'.format(access_token)}) self.assertEqual(response.status_code, 200) self.assertIn("Book returned successfully.", str(response.data)) # Test to test whether a logged in user can return a book not borrowed response = self.client.put('/api/v2/users/book/1', data=json.dumps(self.book), headers={'content-type': 'application/json', 'Authorization': 'Bearer {}'.format(access_token)}) self.assertEqual(response.status_code, 403) self.assertIn("This book is not borrowed.", str(response.data)) # Test to test whether a logged in user can return a book not borrowed response = self.client.put('/api/v2/users/book/3', data=json.dumps(self.book), headers={'content-type': 'application/json', 'Authorization': 'Bearer {}'.format(access_token)}) self.assertEqual(response.status_code, 403) self.assertIn("Book does not exist.", str(response.data)) #Test to view borrowing history response = self.client.get('/api/v2/users/books', headers={'content-type': 'application/json', 'Authorization': 'Bearer {}'.format(access_token)}) self.assertEqual(response.status_code, 200) def test_borrowing_history(self): access_token = UserTestCase.register_login_user(self) response = self.client.get('/api/v2/users/books', headers={'content-type': 'application/json', 'Authorization': 'Bearer {}'.format(access_token)}) self.assertEqual(response.status_code, 200) def tearDown(self): """ Drop all tables after tests are complete. :return: """ with self.app.app_context(): db.session.remove() db.drop_all() if __name__ == '__main__': unittest.main()
{"/api/books/views.py": ["/api/models.py", "/api/books/__init__.py", "/api/decorators.py"], "/api/errors/handlers.py": ["/api/__init__.py"], "/api/users/views.py": ["/api/models.py"], "/tests/test_admin.py": ["/api/__init__.py"], "/tests/test_users.py": ["/api/__init__.py"], "/api/admin/views.py": ["/api/models.py", "/api/decorators.py"], "/api/decorators.py": ["/api/models.py"], "/tests/test_books.py": ["/api/__init__.py", "/tests/test_users.py", "/tests/test_admin.py"], "/api/__init__.py": ["/api/models.py", "/config.py", "/api/books/__init__.py"]}
45,158
brian-mecha/hello-books
refs/heads/challenge_3
/api/__init__.py
from flask_api import FlaskAPI from flask_login import LoginManager from flask_jwt_extended import JWTManager from api.models import RevokedTokens, db from flask_cors import CORS from config import config_app login_manager = LoginManager() jwt = JWTManager() def create_app(config_name): app = FlaskAPI(__name__, instance_relative_config=True) CORS(app) app.config.from_object(config_app[config_name]) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.url_map.strict_slashes = False from .admin import admin as admin_blueprint app.register_blueprint(admin_blueprint) from .books import book as book_blueprint app.register_blueprint(book_blueprint) from .users import user as user_blueprint app.register_blueprint(user_blueprint) from .errors import errors as errors_blueprint app.register_blueprint(errors_blueprint) app.config['SECRET_KEY'] = '\xe3\x8cw\xbdx\x0f\x9c\x91\xcf\x91\x81\xbdZ\xdc$\xedk!\xce\x19\xaa\xcb\xb7~' app.config['BCRYPT_LOG_ROUNDS'] = 15 app.config['JWT_SECRET_KEY'] = '\xe3\x8cw\xbdx\x0f\x9c\x91\xcf\x91\x81\xbdZ\xdc$\xedk!\xce\x19\xaa\xcb\xb7~' app.config['JWT_BLACKLIST_ENABLED'] = True app.config['JWT_BLACKLIST_TOKEN_CHECKS'] = ['access'] db.init_app(app) jwt.init_app(app) login_manager.init_app(app) login_manager.login_message = "Login is required to access this feature." return app
{"/api/books/views.py": ["/api/models.py", "/api/books/__init__.py", "/api/decorators.py"], "/api/errors/handlers.py": ["/api/__init__.py"], "/api/users/views.py": ["/api/models.py"], "/tests/test_admin.py": ["/api/__init__.py"], "/tests/test_users.py": ["/api/__init__.py"], "/api/admin/views.py": ["/api/models.py", "/api/decorators.py"], "/api/decorators.py": ["/api/models.py"], "/tests/test_books.py": ["/api/__init__.py", "/tests/test_users.py", "/tests/test_admin.py"], "/api/__init__.py": ["/api/models.py", "/config.py", "/api/books/__init__.py"]}
45,160
hqwisen/django-oauth2-login-client
refs/heads/master
/oauth2_login_client/utils.py
from django.conf import settings from requests_oauthlib.oauth2_session import OAuth2Session def oauth_session(token=None): return OAuth2Session( settings.OAUTH_CLIENT_ID, redirect_uri=settings.OAUTH_CALLBACK_URL, auto_refresh_url=settings.OAUTH_SERVER + settings.OAUTH_TOKEN_URL, token=token, ) def get_login_url(): oauth = oauth_session() auth_url = settings.OAUTH_SERVER + settings.OAUTH_AUTHORIZATION_URL authorization_url, state = oauth.authorization_url(auth_url, approval_prompt="auto") return dict( authorization_url=authorization_url, state=state, ) def sync_user(user, userdata): """Overwrite user details with data from the remote auth server""" for k in ['email', 'first_name', 'last_name']: if getattr(user, k) != userdata[k]: setattr(user, k, userdata[k]) user.save() try: from allauth.account.models import EmailAddress except ImportError: return # Sync email address list for e in user.emailaddress_set.all(): if e.email not in userdata['email_addresses']: e.delete() for e in userdata['email_addresses']: if user.emailaddress_set.filter(email=e).exists(): continue emailaddress = EmailAddress(email=e) emailaddress.save() user.emailaddress_set.add(emailaddress)
{"/oauth2_login_client/backends.py": ["/oauth2_login_client/utils.py"]}
45,161
hqwisen/django-oauth2-login-client
refs/heads/master
/oauth2_login_client/backends.py
import logging import json from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend from .models import RemoteUser from .utils import oauth_session, sync_user class OAuthBackend(ModelBackend): def authenticate(self, code=None): oauth = oauth_session() token = oauth.fetch_token( settings.OAUTH_SERVER + settings.OAUTH_TOKEN_URL, code=code, client_secret=settings.OAUTH_CLIENT_SECRET, verify=getattr(settings, 'OAUTH_VERIFY_SSL', True), ) r = oauth.get(settings.OAUTH_SERVER + settings.OAUTH_RESOURCE_URL) if r.status_code != 200: logging.warn("Error response from auth server") return None userdata = json.loads(r.content.decode('UTF-8')) if not userdata or 'email' not in userdata or 'username' not in userdata: logging.warn("Username and email not returned by auth server") return None site_code = getattr(settings, 'OAUTH_RESOURCE_CLIENT_CODE', None) if site_code and site_code not in userdata.get('sites', []): logging.info("User not authorised for client site") return None usermodel = get_user_model() try: user = usermodel.objects.get( remoteuser__remote_username=userdata['username']) except usermodel.DoesNotExist: # Create user new_username = userdata['username'][:30] i = 0 while usermodel.objects.filter(username=new_username).exists(): if i > 1000: return None i += 1 new_username = userdata['username'][:30-len(str(i))] + str(i) user = usermodel.objects.create_user( username = new_username, email = userdata['email'], first_name = userdata['first_name'], last_name = userdata['last_name'], ) user.save() user.remoteuser = RemoteUser( user=user, remote_username = userdata['username']) user.remoteuser.save() sync_user(user, userdata) # Send the token back along with the user user.oauth_token = token return user
{"/oauth2_login_client/backends.py": ["/oauth2_login_client/utils.py"]}
45,162
Chriz4/prepabrik
refs/heads/master
/prepabrik/urls.py
from django.contrib import admin from django.urls import path from .views import home_page from produksi.views import ( produksi_list, tambah_barang ) from penjualan.views import (penjualan_list, TransactionCreate ) urlpatterns = [ path('', home_page), path('produksi/', produksi_list, name='produksi'), path('tambah/', tambah_barang, name='tambah'), path('penjualan/', penjualan_list, name='penjualan'), path('transaksi/', TransactionCreate.as_view(), name='transaksi'), path('admin/', admin.site.urls), ]
{"/prepabrik/urls.py": ["/prepabrik/views.py", "/produksi/views.py", "/penjualan/views.py"], "/penjualan/views.py": ["/penjualan/models.py"], "/produksi/admin.py": ["/produksi/models.py"], "/produksi/views.py": ["/produksi/models.py", "/produksi/forms.py"], "/penjualan/admin.py": ["/penjualan/models.py"], "/prepabrik/views.py": ["/produksi/models.py"], "/produksi/forms.py": ["/produksi/models.py"]}
45,163
Chriz4/prepabrik
refs/heads/master
/penjualan/views.py
from django.shortcuts import render from django.views.generic import CreateView from .models import Transaksi # Create your views here. def penjualan_list(request): template_name = "penjualan/penjualan-list.html" qs = Transaksi.objects.all() context = { "page_title": "Log Transaksi", "object_list": qs } return render(request, template_name, context) # def transaksi(request): # template_name = "penjualan/transaksi.html" # context = { "page_title": "Transaksi" } # return render(request, template_name, context) class TransactionCreate(CreateView): model = Transaksi fields = ['barang', 'pembeli', 'telp', 'jumlah', 'harga']
{"/prepabrik/urls.py": ["/prepabrik/views.py", "/produksi/views.py", "/penjualan/views.py"], "/penjualan/views.py": ["/penjualan/models.py"], "/produksi/admin.py": ["/produksi/models.py"], "/produksi/views.py": ["/produksi/models.py", "/produksi/forms.py"], "/penjualan/admin.py": ["/penjualan/models.py"], "/prepabrik/views.py": ["/produksi/models.py"], "/produksi/forms.py": ["/produksi/models.py"]}
45,164
Chriz4/prepabrik
refs/heads/master
/produksi/migrations/0006_auto_20190625_2116.py
# Generated by Django 2.2 on 2019-06-25 14:16 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('produksi', '0005_auto_20190618_1637'), ] operations = [ migrations.AlterField( model_name='logbarang', name='waktu', field=models.DateTimeField(blank=True, null=True), ), ]
{"/prepabrik/urls.py": ["/prepabrik/views.py", "/produksi/views.py", "/penjualan/views.py"], "/penjualan/views.py": ["/penjualan/models.py"], "/produksi/admin.py": ["/produksi/models.py"], "/produksi/views.py": ["/produksi/models.py", "/produksi/forms.py"], "/penjualan/admin.py": ["/penjualan/models.py"], "/prepabrik/views.py": ["/produksi/models.py"], "/produksi/forms.py": ["/produksi/models.py"]}
45,165
Chriz4/prepabrik
refs/heads/master
/produksi/migrations/0004_auto_20190618_1624.py
# Generated by Django 2.2 on 2019-06-18 09:24 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('produksi', '0003_auto_20190618_1623'), ] operations = [ migrations.AlterField( model_name='listbarang', name='waktu', field=models.DateTimeField(), ), ]
{"/prepabrik/urls.py": ["/prepabrik/views.py", "/produksi/views.py", "/penjualan/views.py"], "/penjualan/views.py": ["/penjualan/models.py"], "/produksi/admin.py": ["/produksi/models.py"], "/produksi/views.py": ["/produksi/models.py", "/produksi/forms.py"], "/penjualan/admin.py": ["/penjualan/models.py"], "/prepabrik/views.py": ["/produksi/models.py"], "/produksi/forms.py": ["/produksi/models.py"]}
45,166
Chriz4/prepabrik
refs/heads/master
/produksi/migrations/0005_auto_20190618_1637.py
# Generated by Django 2.2 on 2019-06-18 09:37 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('produksi', '0004_auto_20190618_1624'), ] operations = [ migrations.RemoveField( model_name='listbarang', name='jumlah', ), migrations.RemoveField( model_name='listbarang', name='waktu', ), migrations.AlterField( model_name='listbarang', name='nama', field=models.TextField(max_length=30), ), migrations.CreateModel( name='LogBarang', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('jumlah', models.IntegerField()), ('waktu', models.DateTimeField()), ('barang', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='produksi.ListBarang')), ], ), ]
{"/prepabrik/urls.py": ["/prepabrik/views.py", "/produksi/views.py", "/penjualan/views.py"], "/penjualan/views.py": ["/penjualan/models.py"], "/produksi/admin.py": ["/produksi/models.py"], "/produksi/views.py": ["/produksi/models.py", "/produksi/forms.py"], "/penjualan/admin.py": ["/penjualan/models.py"], "/prepabrik/views.py": ["/produksi/models.py"], "/produksi/forms.py": ["/produksi/models.py"]}
45,167
Chriz4/prepabrik
refs/heads/master
/produksi/admin.py
from django.contrib import admin from .models import ListBarang, LogBarang # Register your models here. admin.site.register(ListBarang) admin.site.register(LogBarang)
{"/prepabrik/urls.py": ["/prepabrik/views.py", "/produksi/views.py", "/penjualan/views.py"], "/penjualan/views.py": ["/penjualan/models.py"], "/produksi/admin.py": ["/produksi/models.py"], "/produksi/views.py": ["/produksi/models.py", "/produksi/forms.py"], "/penjualan/admin.py": ["/penjualan/models.py"], "/prepabrik/views.py": ["/produksi/models.py"], "/produksi/forms.py": ["/produksi/models.py"]}
45,168
Chriz4/prepabrik
refs/heads/master
/produksi/views.py
from django.shortcuts import render, redirect from django.db.models import Sum from .models import LogBarang, ListBarang from .forms import LogBarangModelForm import datetime # Create your views here. def produksi_list(request): template_name = "produksi/list-produksi.html" log_barang = LogBarang.objects.all().order_by('-waktu') page_title = "Log Produksi" # Hitung total semua barang qbarang = LogBarang.objects.all().aggregate(Sum('jumlah')) jumlah_barang = qbarang['jumlah__sum'] #Hitung total masing-masing barang jenis_barang = ListBarang.objects.all() dictmasing = {} for brg in range(1, ListBarang.objects.all().count()+1): dictmasing.update({jenis_barang[brg-1]:LogBarang.objects.filter(barang=brg).aggregate(Sum('jumlah'))['jumlah__sum']}) # print(jumlah_barang) context = {"page_title":page_title, "log_barang": log_barang, "jumlah_barang":jumlah_barang, "dictmasing":dictmasing, "jenis_barang":jenis_barang} return render(request, template_name, context) def tambah_barang(request): form = LogBarangModelForm(request.POST or None) if form.is_valid(): # print(form) obj = form.save(commit=False) obj.waktu = datetime.datetime.now() obj.save() return redirect('/produksi') # form = LogBarangModelForm() template_name = "produksi/form.html" context = {'form':form} return render(request, template_name, context)
{"/prepabrik/urls.py": ["/prepabrik/views.py", "/produksi/views.py", "/penjualan/views.py"], "/penjualan/views.py": ["/penjualan/models.py"], "/produksi/admin.py": ["/produksi/models.py"], "/produksi/views.py": ["/produksi/models.py", "/produksi/forms.py"], "/penjualan/admin.py": ["/penjualan/models.py"], "/prepabrik/views.py": ["/produksi/models.py"], "/produksi/forms.py": ["/produksi/models.py"]}
45,169
Chriz4/prepabrik
refs/heads/master
/penjualan/admin.py
from django.contrib import admin from .models import DaftarBarang, Transaksi # Register your models here. admin.site.register(DaftarBarang) admin.site.register(Transaksi)
{"/prepabrik/urls.py": ["/prepabrik/views.py", "/produksi/views.py", "/penjualan/views.py"], "/penjualan/views.py": ["/penjualan/models.py"], "/produksi/admin.py": ["/produksi/models.py"], "/produksi/views.py": ["/produksi/models.py", "/produksi/forms.py"], "/penjualan/admin.py": ["/penjualan/models.py"], "/prepabrik/views.py": ["/produksi/models.py"], "/produksi/forms.py": ["/produksi/models.py"]}
45,170
Chriz4/prepabrik
refs/heads/master
/produksi/models.py
from django.db import models # import datetime # Create your models here. class ListBarang(models.Model): nama = models.TextField(max_length=30) def __str__(self): return self.nama class LogBarang(models.Model): # now = datetime.datetime.now() barang = models.ForeignKey( ListBarang, on_delete=models.CASCADE ) jumlah = models.IntegerField() waktu = models.DateTimeField(null=True, blank=True) def __str__(self): return str(self.id)
{"/prepabrik/urls.py": ["/prepabrik/views.py", "/produksi/views.py", "/penjualan/views.py"], "/penjualan/views.py": ["/penjualan/models.py"], "/produksi/admin.py": ["/produksi/models.py"], "/produksi/views.py": ["/produksi/models.py", "/produksi/forms.py"], "/penjualan/admin.py": ["/penjualan/models.py"], "/prepabrik/views.py": ["/produksi/models.py"], "/produksi/forms.py": ["/produksi/models.py"]}
45,171
Chriz4/prepabrik
refs/heads/master
/penjualan/migrations/0003_auto_20190703_1003.py
# Generated by Django 2.2 on 2019-07-03 03:03 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('penjualan', '0002_auto_20190627_1943'), ] operations = [ migrations.AlterField( model_name='transaksi', name='pembeli', field=models.CharField(max_length=30), ), migrations.AlterField( model_name='transaksi', name='telp', field=models.CharField(max_length=20), ), migrations.AlterField( model_name='transaksi', name='waktu', field=models.DateTimeField(blank=True, default=django.utils.timezone.now, null=True), ), ]
{"/prepabrik/urls.py": ["/prepabrik/views.py", "/produksi/views.py", "/penjualan/views.py"], "/penjualan/views.py": ["/penjualan/models.py"], "/produksi/admin.py": ["/produksi/models.py"], "/produksi/views.py": ["/produksi/models.py", "/produksi/forms.py"], "/penjualan/admin.py": ["/penjualan/models.py"], "/prepabrik/views.py": ["/produksi/models.py"], "/produksi/forms.py": ["/produksi/models.py"]}
45,172
Chriz4/prepabrik
refs/heads/master
/prepabrik/views.py
from django.http import HttpResponse from django.shortcuts import render from produksi.models import LogBarang def home_page(request): ls = LogBarang.objects.all()[:3] title = 'Sistem Informasi Pabrik' template_name = "home.html" context = {"title": title,'list_barang':ls} return render(request, template_name, context)
{"/prepabrik/urls.py": ["/prepabrik/views.py", "/produksi/views.py", "/penjualan/views.py"], "/penjualan/views.py": ["/penjualan/models.py"], "/produksi/admin.py": ["/produksi/models.py"], "/produksi/views.py": ["/produksi/models.py", "/produksi/forms.py"], "/penjualan/admin.py": ["/penjualan/models.py"], "/prepabrik/views.py": ["/produksi/models.py"], "/produksi/forms.py": ["/produksi/models.py"]}
45,173
Chriz4/prepabrik
refs/heads/master
/produksi/forms.py
from django import forms from .models import LogBarang class LogBarangModelForm(forms.ModelForm): # barang = forms.ChoiceField(widget=Select) class Meta: model = LogBarang fields = ['barang', 'jumlah'] def __init__(self, *args, **kwargs): super(LogBarangModelForm, self).__init__(*args, **kwargs) self.fields['barang'].widget.attrs.update({ 'class': 'form-control' }) self.fields['jumlah'].widget=forms.NumberInput(attrs={ 'class': 'form-control' })
{"/prepabrik/urls.py": ["/prepabrik/views.py", "/produksi/views.py", "/penjualan/views.py"], "/penjualan/views.py": ["/penjualan/models.py"], "/produksi/admin.py": ["/produksi/models.py"], "/produksi/views.py": ["/produksi/models.py", "/produksi/forms.py"], "/penjualan/admin.py": ["/penjualan/models.py"], "/prepabrik/views.py": ["/produksi/models.py"], "/produksi/forms.py": ["/produksi/models.py"]}
45,174
Chriz4/prepabrik
refs/heads/master
/penjualan/models.py
from django.db import models from django.utils import timezone from django.urls import reverse # Create your models here. class DaftarBarang(models.Model): nama = models.TextField(max_length=30) harga = models.IntegerField() def __str__(self): return self.nama class Transaksi(models.Model): barang = models.ForeignKey( DaftarBarang, on_delete=models.CASCADE ) pembeli = models.CharField(max_length=30) telp = models.CharField(max_length=20) jumlah = models.IntegerField() harga = models.BigIntegerField() waktu = models.DateTimeField(null=True, blank=True, default=timezone.now) def __str__(self): return self.pembeli def get_absolute_url(self): return reverse('penjualan')
{"/prepabrik/urls.py": ["/prepabrik/views.py", "/produksi/views.py", "/penjualan/views.py"], "/penjualan/views.py": ["/penjualan/models.py"], "/produksi/admin.py": ["/produksi/models.py"], "/produksi/views.py": ["/produksi/models.py", "/produksi/forms.py"], "/penjualan/admin.py": ["/penjualan/models.py"], "/prepabrik/views.py": ["/produksi/models.py"], "/produksi/forms.py": ["/produksi/models.py"]}
45,175
Chriz4/prepabrik
refs/heads/master
/produksi/migrations/0002_auto_20190618_1425.py
# Generated by Django 2.2 on 2019-06-18 07:25 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('produksi', '0001_initial'), ] operations = [ migrations.AddField( model_name='listbarang', name='jumlah', field=models.IntegerField(default=20), preserve_default=False, ), migrations.AddField( model_name='listbarang', name='waktu', field=models.TimeField(auto_now=True), ), ]
{"/prepabrik/urls.py": ["/prepabrik/views.py", "/produksi/views.py", "/penjualan/views.py"], "/penjualan/views.py": ["/penjualan/models.py"], "/produksi/admin.py": ["/produksi/models.py"], "/produksi/views.py": ["/produksi/models.py", "/produksi/forms.py"], "/penjualan/admin.py": ["/penjualan/models.py"], "/prepabrik/views.py": ["/produksi/models.py"], "/produksi/forms.py": ["/produksi/models.py"]}
45,229
MulticsYin/MulticsSH
refs/heads/master
/need_install/Django-1.8.17/tests/fixtures_migration/models.py
from django.db import models class Book(models.Model): name = models.CharField(max_length=100)
{"/home/admin.py": ["/home/models.py"], "/need_install/Django-1.8.17/tests/fixtures_migration/tests.py": ["/need_install/Django-1.8.17/tests/fixtures_migration/models.py"], "/home/views.py": ["/home/models.py"]}
45,230
MulticsYin/MulticsSH
refs/heads/master
/need_install/Django-1.8.17/tests/utils_tests/test_timezone.py
import copy import datetime import pickle import unittest from django.test import override_settings from django.utils import timezone try: import pytz except ImportError: pytz = None if pytz is not None: CET = pytz.timezone("Europe/Paris") EAT = timezone.get_fixed_timezone(180) # Africa/Nairobi ICT = timezone.get_fixed_timezone(420) # Asia/Bangkok class TimezoneTests(unittest.TestCase): def test_localtime(self): now = datetime.datetime.utcnow().replace(tzinfo=timezone.utc) local_tz = timezone.LocalTimezone() local_now = timezone.localtime(now, local_tz) self.assertEqual(local_now.tzinfo, local_tz) def test_localtime_naive(self): with self.assertRaises(ValueError): timezone.localtime(datetime.datetime.now()) def test_localtime_out_of_range(self): local_tz = timezone.LocalTimezone() long_ago = datetime.datetime(1900, 1, 1, tzinfo=timezone.utc) try: timezone.localtime(long_ago, local_tz) except (OverflowError, ValueError) as exc: self.assertIn("install pytz", exc.args[0]) else: raise unittest.SkipTest("Failed to trigger an OverflowError or ValueError") def test_now(self): with override_settings(USE_TZ=True): self.assertTrue(timezone.is_aware(timezone.now())) with override_settings(USE_TZ=False): self.assertTrue(timezone.is_naive(timezone.now())) def test_override(self): default = timezone.get_default_timezone() try: timezone.activate(ICT) with timezone.override(EAT): self.assertIs(EAT, timezone.get_current_timezone()) self.assertIs(ICT, timezone.get_current_timezone()) with timezone.override(None): self.assertIs(default, timezone.get_current_timezone()) self.assertIs(ICT, timezone.get_current_timezone()) timezone.deactivate() with timezone.override(EAT): self.assertIs(EAT, timezone.get_current_timezone()) self.assertIs(default, timezone.get_current_timezone()) with timezone.override(None): self.assertIs(default, timezone.get_current_timezone()) self.assertIs(default, timezone.get_current_timezone()) finally: timezone.deactivate() def test_override_decorator(self): default = timezone.get_default_timezone() @timezone.override(EAT) def func_tz_eat(): self.assertIs(EAT, timezone.get_current_timezone()) @timezone.override(None) def func_tz_none(): self.assertIs(default, timezone.get_current_timezone()) try: timezone.activate(ICT) func_tz_eat() self.assertIs(ICT, timezone.get_current_timezone()) func_tz_none() self.assertIs(ICT, timezone.get_current_timezone()) timezone.deactivate() func_tz_eat() self.assertIs(default, timezone.get_current_timezone()) func_tz_none() self.assertIs(default, timezone.get_current_timezone()) finally: timezone.deactivate() def test_copy(self): self.assertIsInstance(copy.copy(timezone.UTC()), timezone.UTC) self.assertIsInstance(copy.copy(timezone.LocalTimezone()), timezone.LocalTimezone) def test_deepcopy(self): self.assertIsInstance(copy.deepcopy(timezone.UTC()), timezone.UTC) self.assertIsInstance(copy.deepcopy(timezone.LocalTimezone()), timezone.LocalTimezone) def test_pickling_unpickling(self): self.assertIsInstance(pickle.loads(pickle.dumps(timezone.UTC())), timezone.UTC) self.assertIsInstance(pickle.loads(pickle.dumps(timezone.LocalTimezone())), timezone.LocalTimezone) def test_is_aware(self): self.assertTrue(timezone.is_aware(datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT))) self.assertFalse(timezone.is_aware(datetime.datetime(2011, 9, 1, 13, 20, 30))) def test_is_naive(self): self.assertFalse(timezone.is_naive(datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT))) self.assertTrue(timezone.is_naive(datetime.datetime(2011, 9, 1, 13, 20, 30))) def test_make_aware(self): self.assertEqual( timezone.make_aware(datetime.datetime(2011, 9, 1, 13, 20, 30), EAT), datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT)) with self.assertRaises(ValueError): timezone.make_aware(datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT), EAT) def test_make_naive(self): self.assertEqual( timezone.make_naive(datetime.datetime(2011, 9, 1, 13, 20, 30, tzinfo=EAT), EAT), datetime.datetime(2011, 9, 1, 13, 20, 30)) self.assertEqual( timezone.make_naive(datetime.datetime(2011, 9, 1, 17, 20, 30, tzinfo=ICT), EAT), datetime.datetime(2011, 9, 1, 13, 20, 30)) with self.assertRaises(ValueError): timezone.make_naive(datetime.datetime(2011, 9, 1, 13, 20, 30), EAT) @unittest.skipIf(pytz is None, "this test requires pytz") def test_make_aware2(self): self.assertEqual( timezone.make_aware(datetime.datetime(2011, 9, 1, 12, 20, 30), CET), CET.localize(datetime.datetime(2011, 9, 1, 12, 20, 30))) with self.assertRaises(ValueError): timezone.make_aware(CET.localize(datetime.datetime(2011, 9, 1, 12, 20, 30)), CET) @unittest.skipIf(pytz is None, "this test requires pytz") def test_make_aware_pytz(self): self.assertEqual( timezone.make_naive(CET.localize(datetime.datetime(2011, 9, 1, 12, 20, 30)), CET), datetime.datetime(2011, 9, 1, 12, 20, 30)) self.assertEqual( timezone.make_naive(pytz.timezone("Asia/Bangkok").localize(datetime.datetime(2011, 9, 1, 17, 20, 30)), CET), datetime.datetime(2011, 9, 1, 12, 20, 30)) with self.assertRaises(ValueError): timezone.make_naive(datetime.datetime(2011, 9, 1, 12, 20, 30), CET)
{"/home/admin.py": ["/home/models.py"], "/need_install/Django-1.8.17/tests/fixtures_migration/tests.py": ["/need_install/Django-1.8.17/tests/fixtures_migration/models.py"], "/home/views.py": ["/home/models.py"]}
45,231
MulticsYin/MulticsSH
refs/heads/master
/need_install/Django-1.8.17/tests/model_meta/test_legacy.py
import warnings from django import test from django.contrib.contenttypes.fields import GenericRelation from django.core.exceptions import FieldDoesNotExist from django.db.models.fields import CharField, related from django.utils.deprecation import RemovedInDjango110Warning from .models import BasePerson, Person from .results import TEST_RESULTS class OptionsBaseTests(test.TestCase): def _map_related_query_names(self, res): return tuple((o.field.related_query_name(), m) for o, m in res) def _map_names(self, res): return tuple((f.name, m) for f, m in res) class M2MTests(OptionsBaseTests): def test_many_to_many_with_model(self): for model, expected_result in TEST_RESULTS['many_to_many_with_model'].items(): with warnings.catch_warnings(record=True) as warning: warnings.simplefilter("always") models = [model for field, model in model._meta.get_m2m_with_model()] self.assertEqual([RemovedInDjango110Warning], [w.message.__class__ for w in warning]) self.assertEqual(models, expected_result) @test.ignore_warnings(category=RemovedInDjango110Warning) class RelatedObjectsTests(OptionsBaseTests): key_name = lambda self, r: r[0] def test_related_objects(self): result_key = 'get_all_related_objects_with_model_legacy' for model, expected in TEST_RESULTS[result_key].items(): objects = model._meta.get_all_related_objects_with_model() self.assertEqual(self._map_related_query_names(objects), expected) def test_related_objects_local(self): result_key = 'get_all_related_objects_with_model_local_legacy' for model, expected in TEST_RESULTS[result_key].items(): objects = model._meta.get_all_related_objects_with_model(local_only=True) self.assertEqual(self._map_related_query_names(objects), expected) def test_related_objects_include_hidden(self): result_key = 'get_all_related_objects_with_model_hidden_legacy' for model, expected in TEST_RESULTS[result_key].items(): objects = model._meta.get_all_related_objects_with_model(include_hidden=True) self.assertEqual( sorted(self._map_names(objects), key=self.key_name), sorted(expected, key=self.key_name) ) def test_related_objects_include_hidden_local_only(self): result_key = 'get_all_related_objects_with_model_hidden_local_legacy' for model, expected in TEST_RESULTS[result_key].items(): objects = model._meta.get_all_related_objects_with_model( include_hidden=True, local_only=True) self.assertEqual( sorted(self._map_names(objects), key=self.key_name), sorted(expected, key=self.key_name) ) def test_related_objects_proxy(self): result_key = 'get_all_related_objects_with_model_proxy_legacy' for model, expected in TEST_RESULTS[result_key].items(): objects = model._meta.get_all_related_objects_with_model( include_proxy_eq=True) self.assertEqual(self._map_related_query_names(objects), expected) def test_related_objects_proxy_hidden(self): result_key = 'get_all_related_objects_with_model_proxy_hidden_legacy' for model, expected in TEST_RESULTS[result_key].items(): objects = model._meta.get_all_related_objects_with_model( include_proxy_eq=True, include_hidden=True) self.assertEqual( sorted(self._map_names(objects), key=self.key_name), sorted(expected, key=self.key_name) ) @test.ignore_warnings(category=RemovedInDjango110Warning) class RelatedM2MTests(OptionsBaseTests): def test_related_m2m_with_model(self): result_key = 'get_all_related_many_to_many_with_model_legacy' for model, expected in TEST_RESULTS[result_key].items(): objects = model._meta.get_all_related_m2m_objects_with_model() self.assertEqual(self._map_related_query_names(objects), expected) def test_related_m2m_local_only(self): result_key = 'get_all_related_many_to_many_local_legacy' for model, expected in TEST_RESULTS[result_key].items(): objects = model._meta.get_all_related_many_to_many_objects(local_only=True) self.assertEqual([o.field.related_query_name() for o in objects], expected) def test_related_m2m_asymmetrical(self): m2m = Person._meta.many_to_many self.assertTrue('following_base' in [f.attname for f in m2m]) related_m2m = Person._meta.get_all_related_many_to_many_objects() self.assertTrue('followers_base' in [o.field.related_query_name() for o in related_m2m]) def test_related_m2m_symmetrical(self): m2m = Person._meta.many_to_many self.assertTrue('friends_base' in [f.attname for f in m2m]) related_m2m = Person._meta.get_all_related_many_to_many_objects() self.assertIn('friends_inherited_rel_+', [o.field.related_query_name() for o in related_m2m]) @test.ignore_warnings(category=RemovedInDjango110Warning) class GetFieldByNameTests(OptionsBaseTests): def test_get_data_field(self): field_info = Person._meta.get_field_by_name('data_abstract') self.assertEqual(field_info[1:], (BasePerson, True, False)) self.assertIsInstance(field_info[0], CharField) def test_get_m2m_field(self): field_info = Person._meta.get_field_by_name('m2m_base') self.assertEqual(field_info[1:], (BasePerson, True, True)) self.assertIsInstance(field_info[0], related.ManyToManyField) def test_get_related_object(self): field_info = Person._meta.get_field_by_name('relating_baseperson') self.assertEqual(field_info[1:], (BasePerson, False, False)) self.assertTrue(field_info[0].auto_created) def test_get_related_m2m(self): field_info = Person._meta.get_field_by_name('relating_people') self.assertEqual(field_info[1:], (None, False, True)) self.assertTrue(field_info[0].auto_created) def test_get_generic_relation(self): field_info = Person._meta.get_field_by_name('generic_relation_base') self.assertEqual(field_info[1:], (None, True, False)) self.assertIsInstance(field_info[0], GenericRelation) def test_get_m2m_field_invalid(self): with warnings.catch_warnings(record=True) as warning: warnings.simplefilter("always") self.assertRaises( FieldDoesNotExist, Person._meta.get_field, **{'field_name': 'm2m_base', 'many_to_many': False} ) self.assertEqual(Person._meta.get_field('m2m_base', many_to_many=True).name, 'm2m_base') # 2 RemovedInDjango110Warning messages should be raised, one for each call of get_field() # with the 'many_to_many' argument. self.assertEqual( [RemovedInDjango110Warning, RemovedInDjango110Warning], [w.message.__class__ for w in warning] ) @test.ignore_warnings(category=RemovedInDjango110Warning) class GetAllFieldNamesTestCase(OptionsBaseTests): def test_get_all_field_names(self): for model, expected_names in TEST_RESULTS['get_all_field_names'].items(): objects = model._meta.get_all_field_names() self.assertEqual(sorted(map(str, objects)), sorted(expected_names))
{"/home/admin.py": ["/home/models.py"], "/need_install/Django-1.8.17/tests/fixtures_migration/tests.py": ["/need_install/Django-1.8.17/tests/fixtures_migration/models.py"], "/home/views.py": ["/home/models.py"]}
45,232
MulticsYin/MulticsSH
refs/heads/master
/home/admin.py
#_*_ coding: utf-8 _*_ from django.contrib import admin from .models import * # Register your models heore. # 两种方法建立数据库与后台的连接 # 本机登录http://127.0.0.1:8000/admin/即可访问后台,前提是使用python manage.py runserver. # 若无管理员,在项目当前目录命令行下输入python manage.py createsuperuser新建管理员。 # 方法一: class tb_userAdmin(admin.ModelAdmin): list_display = ('sh_id','sh_username','sh_password','sh_email','sh_token','sh_token_exptime','sh_regtime','sh_status','sh_apikey','sh_about') class tb_user_tokenAdmin(admin.ModelAdmin): list_display = ('sh_user_id','sh_token','sh_deadline') class tb_deviceAdmin(admin.ModelAdmin): list_display = ('sh_id','sh_name','sh_tags','sh_locate','sh_about','sh_user_id','sh_create_time','sh_last_active','sh_status') class tb_sensorAdmin(admin.ModelAdmin): list_display = ('sh_id','sh_name','sh_tags','sh_type','sh_about','sh_device_id','sh_last_update','sh_last_data','sh_status') class tb_sensor_typeAdmin(admin.ModelAdmin): list_display = ('sh_id','sh_name','sh_description','sh_status') class tb_datapoint_listAdmin(admin.ModelAdmin): list_display = ('sh_id','sh_sensor_id','sh_timestamp','sh_value') admin.site.register(tb_user, tb_userAdmin) admin.site.register(tb_user_token, tb_user_tokenAdmin) admin.site.register(tb_device, tb_deviceAdmin) admin.site.register(tb_sensor, tb_sensorAdmin) admin.site.register(tb_sensor_type, tb_sensor_typeAdmin) admin.site.register(tb_datapoint_list, tb_datapoint_listAdmin) # 方法二: ''' admin.site.register(tb_user) admin.site.register(tb_user_token) admin.site.register(tb_device) admin.site.register(tb_sensor) admin.site.register(tb_sensor_type) admin.site.register(tb_datapoint_list) '''
{"/home/admin.py": ["/home/models.py"], "/need_install/Django-1.8.17/tests/fixtures_migration/tests.py": ["/need_install/Django-1.8.17/tests/fixtures_migration/models.py"], "/home/views.py": ["/home/models.py"]}
45,233
MulticsYin/MulticsSH
refs/heads/master
/home/models.py
# _*_ coding: utf-8 _*_ # 模型主要与数据库的表项有关,每一个类对应数据库里的一个表。 # 每个表备注了使用的基本信息,更多详见开发文档《智能家居云平台实现》。 # 注:每个模型重定义的__str__或__unicode__返回值不能以id结尾,会报错。 # 在设计文档中命名表的变量和实际开发的有区别,具体是前面加了一个“sh_”,保证变量唯一。 from __future__ import unicode_literals from django.db import models from django.utils.encoding import python_2_unicode_compatible from DjangoUeditor.models import UEditorField from django.core.urlresolvers import reverse # 用户表(tb_user),用于保存用户的基本信息。 @python_2_unicode_compatible class tb_user(models.Model): sh_id = models.IntegerField(db_index=True) # 用户ID sh_username = models.CharField(max_length=20) # 用户名 sh_password = models.CharField(max_length=100) # 密码密文 sh_email = models.CharField(max_length=50) # 验证邮箱 sh_token = models.CharField(max_length=50) # 验证令牌 sh_token_exptime = models.DateField() # 令牌失效时间 sh_regtime = models.DateField() # 注册时间戳 sh_status = models.BooleanField(default=False) # 状态:激活与否 sh_apikey = models.CharField(max_length=100) # APIKEY,用于授权API操作 sh_about = UEditorField('内容', height=300, width=1000,default=u'', blank=True, imagePath="uploads/images/",toolbars='besttome', filePath='uploads/files/') # 用户信息的描述 def __str__(self): return self.sh_username # 模型必须返回一个__str__或__unicode__,__unicode__如下: # def __unicode__(self): # return self.sh_username # 一个实验性的接口,保留以方便后续开发。 # def get_absolute_url(self): # return reverse('tb_user', args=(self.sh_id,)) # 用户令牌表(tb_user_token)用于保存用户的令牌,该令牌在用户每次登陆时重新 # 生成,并确保唯一,一定时间后会自动失效,需要重新登陆。 @python_2_unicode_compatible class tb_user_token(models.Model): sh_user_id = models.IntegerField(db_index=True) # 用户ID sh_token = models.CharField(max_length=100) # 用户令牌 sh_deadline = models.IntegerField() # 截止时间、失效时间 def __str__(self): return self.sh_token # 设备表(tb_device)用于保存无线智能家居系统设备信息。 @python_2_unicode_compatible class tb_device(models.Model): sh_id = models.IntegerField(db_index=True) # 设备ID sh_name = models.CharField(max_length=50) # 设备名称 sh_tags = models.CharField(max_length=50) # 设备标签 sh_locate = models.CharField(max_length=50) # 设备位置 sh_user_id = models.IntegerField() # 用户ID sh_create_time = models.DateField() # 创建时间 sh_last_active = models.DateField() # 最后活动时间 sh_status = models.BooleanField(default=False) # 状态 sh_about = UEditorField('内容', height=300, width=1000,default=u'', blank=True,imagePath="uploads/images/",toolbars='besttome', filePath='uploads/files/') # 设备表信息描述 def __str__(self): return self.sh_name # 传感器表(tb_sensor)用于保存无线智能家居系统设备所包含的传感器的信息, # 一个设备可能包含有多个传感器。 @python_2_unicode_compatible class tb_sensor(models.Model): sh_id = models.IntegerField(db_index=True) # 传感器ID sh_name = models.CharField(max_length=50) # 传感器名称 sh_tags = models.CharField(max_length=50) # 传感器标签 sh_type = models.IntegerField() # 传感器类型ID sh_device_id = models.IntegerField() # 设备ID sh_last_update = models.DateField() # 更新时间 sh_last_data = models.TextField() # 最新数据 sh_status = models.BooleanField(default=False) # 状态 sh_about = UEditorField('内容', height=300, width=1000,default=u'', blank=True,imagePath="uploads/images/",toolbars='besttome', filePath='uploads/files/') # 传感器信息的描述 def __str__(self): return self.sh_name # 传感器类型表(tb_sensor_type)用于保存传感器的类型及描述,创建该表的目 # 的在于方便扩展传感器类型。 @python_2_unicode_compatible class tb_sensor_type(models.Model): sh_id = models.IntegerField(db_index=True) # 传感器类型ID sh_name = models.CharField(max_length=50) # 类型名称 sh_description = models.TextField() # 对该类型的描述 sh_status = models.BooleanField(default=False) # 状态 def __str__(self): return self.sh_name # 数据点表(tb_datapoint_lite)用于保存传感器的数据,每一条记录都是某个传 # 感器的某个时间点下的数据。 @python_2_unicode_compatible class tb_datapoint_list(models.Model): sh_id = models.IntegerField(db_index=True) # 数据点ID sh_sensor_id = models.IntegerField() # 传感器ID sh_timestamp = models.IntegerField() # 时间戳 sh_value = UEditorField('内容', height=300, width=1000,default=u'', blank=True,imagePath="uploads/images/",toolbars='besttome', filePath='uploads/files/') # 数据值 def __str__(self): return self.sh_value
{"/home/admin.py": ["/home/models.py"], "/need_install/Django-1.8.17/tests/fixtures_migration/tests.py": ["/need_install/Django-1.8.17/tests/fixtures_migration/models.py"], "/home/views.py": ["/home/models.py"]}
45,234
MulticsYin/MulticsSH
refs/heads/master
/need_install/Django-1.8.17/tests/app_loading/tests.py
from __future__ import unicode_literals import os import sys import warnings from django.apps import apps from django.core.exceptions import ImproperlyConfigured from django.db import models from django.test import TestCase from django.test.utils import extend_sys_path from django.utils import six from django.utils._os import upath from django.utils.deprecation import RemovedInDjango19Warning class EggLoadingTest(TestCase): def setUp(self): self.egg_dir = '%s/eggs' % os.path.dirname(upath(__file__)) def tearDown(self): apps.clear_cache() def test_egg1(self): """Models module can be loaded from an app in an egg""" egg_name = '%s/modelapp.egg' % self.egg_dir with extend_sys_path(egg_name): with self.settings(INSTALLED_APPS=['app_with_models']): models_module = apps.get_app_config('app_with_models').models_module self.assertIsNotNone(models_module) del apps.all_models['app_with_models'] def test_egg2(self): """Loading an app from an egg that has no models returns no models (and no error)""" egg_name = '%s/nomodelapp.egg' % self.egg_dir with extend_sys_path(egg_name): with self.settings(INSTALLED_APPS=['app_no_models']): models_module = apps.get_app_config('app_no_models').models_module self.assertIsNone(models_module) del apps.all_models['app_no_models'] def test_egg3(self): """Models module can be loaded from an app located under an egg's top-level package""" egg_name = '%s/omelet.egg' % self.egg_dir with extend_sys_path(egg_name): with self.settings(INSTALLED_APPS=['omelet.app_with_models']): models_module = apps.get_app_config('app_with_models').models_module self.assertIsNotNone(models_module) del apps.all_models['app_with_models'] def test_egg4(self): """Loading an app with no models from under the top-level egg package generates no error""" egg_name = '%s/omelet.egg' % self.egg_dir with extend_sys_path(egg_name): with self.settings(INSTALLED_APPS=['omelet.app_no_models']): models_module = apps.get_app_config('app_no_models').models_module self.assertIsNone(models_module) del apps.all_models['app_no_models'] def test_egg5(self): """Loading an app from an egg that has an import error in its models module raises that error""" egg_name = '%s/brokenapp.egg' % self.egg_dir with extend_sys_path(egg_name): with six.assertRaisesRegex(self, ImportError, 'modelz'): with self.settings(INSTALLED_APPS=['broken_app']): pass class GetModelsTest(TestCase): def setUp(self): from .not_installed import models self.not_installed_module = models def test_get_model_only_returns_installed_models(self): with self.assertRaises(LookupError): apps.get_model("not_installed", "NotInstalledModel") def test_get_models_only_returns_installed_models(self): self.assertNotIn( "NotInstalledModel", [m.__name__ for m in apps.get_models()]) def test_exception_raised_if_model_declared_outside_app(self): class FakeModule(models.Model): __name__ = str("models_that_do_not_live_in_an_app") sys.modules['models_not_in_app'] = FakeModule def declare_model_outside_app(): models.base.ModelBase.__new__( models.base.ModelBase, str('Outsider'), (models.Model,), {'__module__': 'models_not_in_app'}) msg = ( 'Unable to detect the app label for model "Outsider." ' 'Ensure that its module, "models_that_do_not_live_in_an_app", ' 'is located inside an installed app.' ) with warnings.catch_warnings(): warnings.filterwarnings('ignore', category=RemovedInDjango19Warning) with self.assertRaisesMessage(ImproperlyConfigured, msg): declare_model_outside_app()
{"/home/admin.py": ["/home/models.py"], "/need_install/Django-1.8.17/tests/fixtures_migration/tests.py": ["/need_install/Django-1.8.17/tests/fixtures_migration/models.py"], "/home/views.py": ["/home/models.py"]}
45,235
MulticsYin/MulticsSH
refs/heads/master
/need_install/Django-1.8.17/tests/commands_sql/tests.py
from __future__ import unicode_literals import re import unittest from django.apps import apps from django.core.management.color import no_style from django.core.management.sql import ( sql_all, sql_create, sql_delete, sql_destroy_indexes, sql_indexes, ) from django.db import DEFAULT_DB_ALIAS, connections from django.test import TestCase, ignore_warnings, override_settings from django.utils import six from django.utils.deprecation import RemovedInDjango110Warning # See also initial_sql_regress for 'custom_sql_for_model' tests class SQLCommandsTestCase(TestCase): """Tests for several functions in django/core/management/sql.py""" def count_ddl(self, output, cmd): return len([o for o in output if o.startswith(cmd)]) def test_sql_create(self): app_config = apps.get_app_config('commands_sql') output = sql_create(app_config, no_style(), connections[DEFAULT_DB_ALIAS]) tables = set() create_table_re = re.compile(r'^create table .(?P<table>[\w_]+).*', re.IGNORECASE) reference_re = re.compile(r'.* references .(?P<table>[\w_]+).*', re.IGNORECASE) for statement in output: create_table = create_table_re.match(statement) if create_table: # Lower since Oracle's table names are upper cased. tables.add(create_table.group('table').lower()) continue reference = reference_re.match(statement) if reference: # Lower since Oracle's table names are upper cased. table = reference.group('table').lower() self.assertIn( table, tables, "The table %s is referenced before its creation." % table ) self.assertEqual(tables, { 'commands_sql_comment', 'commands_sql_book', 'commands_sql_book_comments' }) @unittest.skipUnless('PositiveIntegerField' in connections[DEFAULT_DB_ALIAS].data_type_check_constraints, 'Backend does not have checks.') def test_sql_create_check(self): """Regression test for #23416 -- Check that db_params['check'] is respected.""" app_config = apps.get_app_config('commands_sql') output = sql_create(app_config, no_style(), connections[DEFAULT_DB_ALIAS]) success = False for statement in output: if 'CHECK' in statement: success = True if not success: self.fail("'CHECK' not found in output %s" % output) def test_sql_delete(self): app_config = apps.get_app_config('commands_sql') output = sql_delete(app_config, no_style(), connections[DEFAULT_DB_ALIAS], close_connection=False) drop_tables = [o for o in output if o.startswith('DROP TABLE')] self.assertEqual(len(drop_tables), 3) # Lower so that Oracle's upper case tbl names wont break sql = drop_tables[-1].lower() six.assertRegex(self, sql, r'^drop table .commands_sql_comment.*') @ignore_warnings(category=RemovedInDjango110Warning) def test_sql_indexes(self): app_config = apps.get_app_config('commands_sql') output = sql_indexes(app_config, no_style(), connections[DEFAULT_DB_ALIAS]) # Number of indexes is backend-dependent self.assertTrue(1 <= self.count_ddl(output, 'CREATE INDEX') <= 4) def test_sql_destroy_indexes(self): app_config = apps.get_app_config('commands_sql') output = sql_destroy_indexes(app_config, no_style(), connections[DEFAULT_DB_ALIAS]) # Number of indexes is backend-dependent self.assertTrue(1 <= self.count_ddl(output, 'DROP INDEX') <= 4) @ignore_warnings(category=RemovedInDjango110Warning) def test_sql_all(self): app_config = apps.get_app_config('commands_sql') output = sql_all(app_config, no_style(), connections[DEFAULT_DB_ALIAS]) self.assertEqual(self.count_ddl(output, 'CREATE TABLE'), 3) # Number of indexes is backend-dependent self.assertTrue(1 <= self.count_ddl(output, 'CREATE INDEX') <= 4) class TestRouter(object): def allow_migrate(self, db, app_label, **hints): return False @override_settings(DATABASE_ROUTERS=[TestRouter()]) class SQLCommandsRouterTestCase(TestCase): def test_router_honored(self): app_config = apps.get_app_config('commands_sql') for sql_command in (sql_all, sql_create, sql_delete, sql_indexes, sql_destroy_indexes): if sql_command is sql_delete: output = sql_command(app_config, no_style(), connections[DEFAULT_DB_ALIAS], close_connection=False) # "App creates no tables in the database. Nothing to do." expected_output = 1 else: output = sql_command(app_config, no_style(), connections[DEFAULT_DB_ALIAS]) expected_output = 0 self.assertEqual(len(output), expected_output, "%s command is not honoring routers" % sql_command.__name__)
{"/home/admin.py": ["/home/models.py"], "/need_install/Django-1.8.17/tests/fixtures_migration/tests.py": ["/need_install/Django-1.8.17/tests/fixtures_migration/models.py"], "/home/views.py": ["/home/models.py"]}
45,236
MulticsYin/MulticsSH
refs/heads/master
/need_install/Django-1.8.17/tests/shortcuts/tests.py
from django.test import TestCase, ignore_warnings, override_settings from django.test.utils import require_jinja2 from django.utils.deprecation import RemovedInDjango110Warning @override_settings( ROOT_URLCONF='shortcuts.urls', ) class ShortcutTests(TestCase): def test_render_to_response(self): response = self.client.get('/render_to_response/') self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b'FOO.BAR..\n') self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8') def test_render_to_response_with_multiple_templates(self): response = self.client.get('/render_to_response/multiple_templates/') self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b'FOO.BAR..\n') @ignore_warnings(category=RemovedInDjango110Warning) def test_render_to_response_with_request_context(self): response = self.client.get('/render_to_response/request_context/') self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b'FOO.BAR../render_to_response/request_context/\n') self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8') def test_render_to_response_with_content_type(self): response = self.client.get('/render_to_response/content_type/') self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b'FOO.BAR..\n') self.assertEqual(response['Content-Type'], 'application/x-rendertest') @ignore_warnings(category=RemovedInDjango110Warning) def test_render_to_response_with_dirs(self): response = self.client.get('/render_to_response/dirs/') self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b'spam eggs\n') self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8') def test_render_to_response_with_status(self): response = self.client.get('/render_to_response/status/') self.assertEqual(response.status_code, 403) self.assertEqual(response.content, b'FOO.BAR..\n') @require_jinja2 def test_render_to_response_with_using(self): response = self.client.get('/render_to_response/using/') self.assertEqual(response.content, b'DTL\n') response = self.client.get('/render_to_response/using/?using=django') self.assertEqual(response.content, b'DTL\n') response = self.client.get('/render_to_response/using/?using=jinja2') self.assertEqual(response.content, b'Jinja2\n') @ignore_warnings(category=RemovedInDjango110Warning) def test_render_to_response_with_context_instance_misuse(self): """ For backwards-compatibility, ensure that it's possible to pass a RequestContext instance in the dictionary argument instead of the context_instance argument. """ response = self.client.get('/render_to_response/context_instance_misuse/') self.assertContains(response, 'context processor output') def test_render(self): response = self.client.get('/render/') self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b'FOO.BAR../render/\n') self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8') self.assertFalse(hasattr(response.context.request, 'current_app')) def test_render_with_multiple_templates(self): response = self.client.get('/render/multiple_templates/') self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b'FOO.BAR../render/multiple_templates/\n') @ignore_warnings(category=RemovedInDjango110Warning) def test_render_with_base_context(self): response = self.client.get('/render/base_context/') self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b'FOO.BAR..\n') self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8') def test_render_with_content_type(self): response = self.client.get('/render/content_type/') self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b'FOO.BAR../render/content_type/\n') self.assertEqual(response['Content-Type'], 'application/x-rendertest') def test_render_with_status(self): response = self.client.get('/render/status/') self.assertEqual(response.status_code, 403) self.assertEqual(response.content, b'FOO.BAR../render/status/\n') @require_jinja2 def test_render_with_using(self): response = self.client.get('/render/using/') self.assertEqual(response.content, b'DTL\n') response = self.client.get('/render/using/?using=django') self.assertEqual(response.content, b'DTL\n') response = self.client.get('/render/using/?using=jinja2') self.assertEqual(response.content, b'Jinja2\n') @ignore_warnings(category=RemovedInDjango110Warning) def test_render_with_current_app(self): response = self.client.get('/render/current_app/') self.assertEqual(response.context.request.current_app, "foobar_app") @ignore_warnings(category=RemovedInDjango110Warning) def test_render_with_dirs(self): response = self.client.get('/render/dirs/') self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b'spam eggs\n') self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8') @ignore_warnings(category=RemovedInDjango110Warning) def test_render_with_current_app_conflict(self): with self.assertRaises(ValueError): self.client.get('/render/current_app_conflict/')
{"/home/admin.py": ["/home/models.py"], "/need_install/Django-1.8.17/tests/fixtures_migration/tests.py": ["/need_install/Django-1.8.17/tests/fixtures_migration/models.py"], "/home/views.py": ["/home/models.py"]}
45,237
MulticsYin/MulticsSH
refs/heads/master
/need_install/Django-1.8.17/tests/template_tests/test_engine.py
import os from django.template import Context from django.template.engine import Engine from django.test import SimpleTestCase, ignore_warnings from django.utils.deprecation import RemovedInDjango110Warning from .utils import ROOT, TEMPLATE_DIR OTHER_DIR = os.path.join(ROOT, 'other_templates') @ignore_warnings(category=RemovedInDjango110Warning) class DeprecatedRenderToStringTest(SimpleTestCase): def setUp(self): self.engine = Engine(dirs=[TEMPLATE_DIR]) def test_basic_context(self): self.assertEqual( self.engine.render_to_string('test_context.html', {'obj': 'test'}), 'obj:test\n', ) def test_existing_context_kept_clean(self): context = Context({'obj': 'before'}) output = self.engine.render_to_string( 'test_context.html', {'obj': 'after'}, context_instance=context, ) self.assertEqual(output, 'obj:after\n') self.assertEqual(context['obj'], 'before') def test_no_empty_dict_pushed_to_stack(self): """ #21741 -- An empty dict should not be pushed to the context stack when render_to_string is called without a context argument. """ # The stack should have a length of 1, corresponding to the builtins self.assertEqual( '1', self.engine.render_to_string('test_context_stack.html').strip(), ) self.assertEqual( '1', self.engine.render_to_string( 'test_context_stack.html', context_instance=Context() ).strip(), ) class LoaderTests(SimpleTestCase): def test_debug_nodelist_name(self): engine = Engine(dirs=[TEMPLATE_DIR], debug=True) template_name = 'index.html' template = engine.get_template(template_name) name = template.nodelist[0].source[0].name self.assertTrue(name.endswith(template_name)) def test_origin(self): engine = Engine(dirs=[TEMPLATE_DIR], debug=True) template = engine.get_template('index.html') self.assertEqual(template.origin.loadname, 'index.html') def test_origin_debug_false(self): engine = Engine(dirs=[TEMPLATE_DIR], debug=False) template = engine.get_template('index.html') self.assertEqual(template.origin, None) def test_loader_priority(self): """ #21460 -- Check that the order of template loader works. """ loaders = [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ] engine = Engine(dirs=[OTHER_DIR, TEMPLATE_DIR], loaders=loaders) template = engine.get_template('priority/foo.html') self.assertEqual(template.render(Context()), 'priority\n') def test_cached_loader_priority(self): """ Check that the order of template loader works. Refs #21460. """ loaders = [ ('django.template.loaders.cached.Loader', [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ]), ] engine = Engine(dirs=[OTHER_DIR, TEMPLATE_DIR], loaders=loaders) template = engine.get_template('priority/foo.html') self.assertEqual(template.render(Context()), 'priority\n') template = engine.get_template('priority/foo.html') self.assertEqual(template.render(Context()), 'priority\n') @ignore_warnings(category=RemovedInDjango110Warning) class TemplateDirsOverrideTests(SimpleTestCase): DIRS = ((OTHER_DIR, ), [OTHER_DIR]) def setUp(self): self.engine = Engine() def test_render_to_string(self): for dirs in self.DIRS: self.assertEqual( self.engine.render_to_string('test_dirs.html', dirs=dirs), 'spam eggs\n', ) def test_get_template(self): for dirs in self.DIRS: template = self.engine.get_template('test_dirs.html', dirs=dirs) self.assertEqual(template.render(Context()), 'spam eggs\n') def test_select_template(self): for dirs in self.DIRS: template = self.engine.select_template(['test_dirs.html'], dirs=dirs) self.assertEqual(template.render(Context()), 'spam eggs\n')
{"/home/admin.py": ["/home/models.py"], "/need_install/Django-1.8.17/tests/fixtures_migration/tests.py": ["/need_install/Django-1.8.17/tests/fixtures_migration/models.py"], "/home/views.py": ["/home/models.py"]}
45,238
MulticsYin/MulticsSH
refs/heads/master
/need_install/Django-1.8.17/tests/template_tests/syntax_tests/test_i18n.py
# coding: utf-8 from __future__ import unicode_literals from django.test import SimpleTestCase from django.utils import translation from django.utils.safestring import mark_safe from ..utils import setup class I18nTagTests(SimpleTestCase): @setup({'i18n01': '{% load i18n %}{% trans \'xxxyyyxxx\' %}'}) def test_i18n01(self): """ simple translation of a string delimited by ' """ output = self.engine.render_to_string('i18n01') self.assertEqual(output, 'xxxyyyxxx') @setup({'i18n02': '{% load i18n %}{% trans "xxxyyyxxx" %}'}) def test_i18n02(self): """ simple translation of a string delimited by " """ output = self.engine.render_to_string('i18n02') self.assertEqual(output, 'xxxyyyxxx') @setup({'i18n03': '{% load i18n %}{% blocktrans %}{{ anton }}{% endblocktrans %}'}) def test_i18n03(self): """ simple translation of a variable """ output = self.engine.render_to_string('i18n03', {'anton': b'\xc3\x85'}) self.assertEqual(output, 'Å') @setup({'i18n04': '{% load i18n %}{% blocktrans with berta=anton|lower %}{{ berta }}{% endblocktrans %}'}) def test_i18n04(self): """ simple translation of a variable and filter """ output = self.engine.render_to_string('i18n04', {'anton': b'\xc3\x85'}) self.assertEqual(output, 'å') @setup({'legacyi18n04': '{% load i18n %}' '{% blocktrans with anton|lower as berta %}{{ berta }}{% endblocktrans %}'}) def test_legacyi18n04(self): """ simple translation of a variable and filter """ output = self.engine.render_to_string('legacyi18n04', {'anton': b'\xc3\x85'}) self.assertEqual(output, 'å') @setup({'i18n05': '{% load i18n %}{% blocktrans %}xxx{{ anton }}xxx{% endblocktrans %}'}) def test_i18n05(self): """ simple translation of a string with interpolation """ output = self.engine.render_to_string('i18n05', {'anton': 'yyy'}) self.assertEqual(output, 'xxxyyyxxx') @setup({'i18n06': '{% load i18n %}{% trans "Page not found" %}'}) def test_i18n06(self): """ simple translation of a string to german """ with translation.override('de'): output = self.engine.render_to_string('i18n06') self.assertEqual(output, 'Seite nicht gefunden') @setup({'i18n07': '{% load i18n %}' '{% blocktrans count counter=number %}singular{% plural %}' '{{ counter }} plural{% endblocktrans %}'}) def test_i18n07(self): """ translation of singular form """ output = self.engine.render_to_string('i18n07', {'number': 1}) self.assertEqual(output, 'singular') @setup({'legacyi18n07': '{% load i18n %}' '{% blocktrans count number as counter %}singular{% plural %}' '{{ counter }} plural{% endblocktrans %}'}) def test_legacyi18n07(self): """ translation of singular form """ output = self.engine.render_to_string('legacyi18n07', {'number': 1}) self.assertEqual(output, 'singular') @setup({'i18n08': '{% load i18n %}' '{% blocktrans count number as counter %}singular{% plural %}' '{{ counter }} plural{% endblocktrans %}'}) def test_i18n08(self): """ translation of plural form """ output = self.engine.render_to_string('i18n08', {'number': 2}) self.assertEqual(output, '2 plural') @setup({'legacyi18n08': '{% load i18n %}' '{% blocktrans count counter=number %}singular{% plural %}' '{{ counter }} plural{% endblocktrans %}'}) def test_legacyi18n08(self): """ translation of plural form """ output = self.engine.render_to_string('legacyi18n08', {'number': 2}) self.assertEqual(output, '2 plural') @setup({'i18n09': '{% load i18n %}{% trans "Page not found" noop %}'}) def test_i18n09(self): """ simple non-translation (only marking) of a string to german """ with translation.override('de'): output = self.engine.render_to_string('i18n09') self.assertEqual(output, 'Page not found') @setup({'i18n10': '{{ bool|yesno:_("yes,no,maybe") }}'}) def test_i18n10(self): """ translation of a variable with a translated filter """ with translation.override('de'): output = self.engine.render_to_string('i18n10', {'bool': True}) self.assertEqual(output, 'Ja') @setup({'i18n11': '{{ bool|yesno:"ja,nein" }}'}) def test_i18n11(self): """ translation of a variable with a non-translated filter """ output = self.engine.render_to_string('i18n11', {'bool': True}) self.assertEqual(output, 'ja') @setup({'i18n12': '{% load i18n %}' '{% get_available_languages as langs %}{% for lang in langs %}' '{% ifequal lang.0 "de" %}{{ lang.0 }}{% endifequal %}{% endfor %}'}) def test_i18n12(self): """ usage of the get_available_languages tag """ output = self.engine.render_to_string('i18n12') self.assertEqual(output, 'de') @setup({'i18n13': '{{ _("Password") }}'}) def test_i18n13(self): """ translation of constant strings """ with translation.override('de'): output = self.engine.render_to_string('i18n13') self.assertEqual(output, 'Passwort') @setup({'i18n14': '{% cycle "foo" _("Password") _(\'Password\') as c %} {% cycle c %} {% cycle c %}'}) def test_i18n14(self): """ translation of constant strings """ with translation.override('de'): output = self.engine.render_to_string('i18n14') self.assertEqual(output, 'foo Passwort Passwort') @setup({'i18n15': '{{ absent|default:_("Password") }}'}) def test_i18n15(self): """ translation of constant strings """ with translation.override('de'): output = self.engine.render_to_string('i18n15', {'absent': ''}) self.assertEqual(output, 'Passwort') @setup({'i18n16': '{{ _("<") }}'}) def test_i18n16(self): """ translation of constant strings """ with translation.override('de'): output = self.engine.render_to_string('i18n16') self.assertEqual(output, '<') @setup({'i18n17': '{% load i18n %}' '{% blocktrans with berta=anton|escape %}{{ berta }}{% endblocktrans %}'}) def test_i18n17(self): """ Escaping inside blocktrans and trans works as if it was directly in the template. """ output = self.engine.render_to_string('i18n17', {'anton': 'α & β'}) self.assertEqual(output, 'α &amp; β') @setup({'i18n18': '{% load i18n %}' '{% blocktrans with berta=anton|force_escape %}{{ berta }}{% endblocktrans %}'}) def test_i18n18(self): output = self.engine.render_to_string('i18n18', {'anton': 'α & β'}) self.assertEqual(output, 'α &amp; β') @setup({'i18n19': '{% load i18n %}{% blocktrans %}{{ andrew }}{% endblocktrans %}'}) def test_i18n19(self): output = self.engine.render_to_string('i18n19', {'andrew': 'a & b'}) self.assertEqual(output, 'a &amp; b') @setup({'i18n20': '{% load i18n %}{% trans andrew %}'}) def test_i18n20(self): output = self.engine.render_to_string('i18n20', {'andrew': 'a & b'}) self.assertEqual(output, 'a &amp; b') @setup({'i18n21': '{% load i18n %}{% blocktrans %}{{ andrew }}{% endblocktrans %}'}) def test_i18n21(self): output = self.engine.render_to_string('i18n21', {'andrew': mark_safe('a & b')}) self.assertEqual(output, 'a & b') @setup({'i18n22': '{% load i18n %}{% trans andrew %}'}) def test_i18n22(self): output = self.engine.render_to_string('i18n22', {'andrew': mark_safe('a & b')}) self.assertEqual(output, 'a & b') @setup({'legacyi18n17': '{% load i18n %}' '{% blocktrans with anton|escape as berta %}{{ berta }}{% endblocktrans %}'}) def test_legacyi18n17(self): output = self.engine.render_to_string('legacyi18n17', {'anton': 'α & β'}) self.assertEqual(output, 'α &amp; β') @setup({'legacyi18n18': '{% load i18n %}' '{% blocktrans with anton|force_escape as berta %}' '{{ berta }}{% endblocktrans %}'}) def test_legacyi18n18(self): output = self.engine.render_to_string('legacyi18n18', {'anton': 'α & β'}) self.assertEqual(output, 'α &amp; β') @setup({'i18n23': '{% load i18n %}{% trans "Page not found"|capfirst|slice:"6:" %}'}) def test_i18n23(self): """ #5972 - Use filters with the {% trans %} tag """ with translation.override('de'): output = self.engine.render_to_string('i18n23') self.assertEqual(output, 'nicht gefunden') @setup({'i18n24': '{% load i18n %}{% trans \'Page not found\'|upper %}'}) def test_i18n24(self): with translation.override('de'): output = self.engine.render_to_string('i18n24') self.assertEqual(output, 'SEITE NICHT GEFUNDEN') @setup({'i18n25': '{% load i18n %}{% trans somevar|upper %}'}) def test_i18n25(self): with translation.override('de'): output = self.engine.render_to_string('i18n25', {'somevar': 'Page not found'}) self.assertEqual(output, 'SEITE NICHT GEFUNDEN') @setup({'i18n26': '{% load i18n %}' '{% blocktrans with extra_field=myextra_field count counter=number %}' 'singular {{ extra_field }}{% plural %}plural{% endblocktrans %}'}) def test_i18n26(self): """ translation of plural form with extra field in singular form (#13568) """ output = self.engine.render_to_string('i18n26', {'myextra_field': 'test', 'number': 1}) self.assertEqual(output, 'singular test') @setup({'legacyi18n26': '{% load i18n %}' '{% blocktrans with myextra_field as extra_field count number as counter %}' 'singular {{ extra_field }}{% plural %}plural{% endblocktrans %}'}) def test_legacyi18n26(self): output = self.engine.render_to_string('legacyi18n26', {'myextra_field': 'test', 'number': 1}) self.assertEqual(output, 'singular test') @setup({'i18n27': '{% load i18n %}{% blocktrans count counter=number %}' '{{ counter }} result{% plural %}{{ counter }} results' '{% endblocktrans %}'}) def test_i18n27(self): """ translation of singular form in russian (#14126) """ with translation.override('ru'): output = self.engine.render_to_string('i18n27', {'number': 1}) self.assertEqual(output, '1 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442') @setup({'legacyi18n27': '{% load i18n %}' '{% blocktrans count number as counter %}{{ counter }} result' '{% plural %}{{ counter }} results{% endblocktrans %}'}) def test_legacyi18n27(self): with translation.override('ru'): output = self.engine.render_to_string('legacyi18n27', {'number': 1}) self.assertEqual(output, '1 \u0440\u0435\u0437\u0443\u043b\u044c\u0442\u0430\u0442') @setup({'i18n28': '{% load i18n %}' '{% blocktrans with a=anton b=berta %}{{ a }} + {{ b }}{% endblocktrans %}'}) def test_i18n28(self): """ simple translation of multiple variables """ output = self.engine.render_to_string('i18n28', {'anton': 'α', 'berta': 'β'}) self.assertEqual(output, 'α + β') @setup({'legacyi18n28': '{% load i18n %}' '{% blocktrans with anton as a and berta as b %}' '{{ a }} + {{ b }}{% endblocktrans %}'}) def test_legacyi18n28(self): output = self.engine.render_to_string('legacyi18n28', {'anton': 'α', 'berta': 'β'}) self.assertEqual(output, 'α + β') # retrieving language information @setup({'i18n28_2': '{% load i18n %}' '{% get_language_info for "de" as l %}' '{{ l.code }}: {{ l.name }}/{{ l.name_local }} bidi={{ l.bidi }}'}) def test_i18n28_2(self): output = self.engine.render_to_string('i18n28_2') self.assertEqual(output, 'de: German/Deutsch bidi=False') @setup({'i18n29': '{% load i18n %}' '{% get_language_info for LANGUAGE_CODE as l %}' '{{ l.code }}: {{ l.name }}/{{ l.name_local }} bidi={{ l.bidi }}'}) def test_i18n29(self): output = self.engine.render_to_string('i18n29', {'LANGUAGE_CODE': 'fi'}) self.assertEqual(output, 'fi: Finnish/suomi bidi=False') @setup({'i18n30': '{% load i18n %}' '{% get_language_info_list for langcodes as langs %}' '{% for l in langs %}{{ l.code }}: {{ l.name }}/' '{{ l.name_local }} bidi={{ l.bidi }}; {% endfor %}'}) def test_i18n30(self): output = self.engine.render_to_string('i18n30', {'langcodes': ['it', 'no']}) self.assertEqual(output, 'it: Italian/italiano bidi=False; no: Norwegian/norsk bidi=False; ') @setup({'i18n31': '{% load i18n %}' '{% get_language_info_list for langcodes as langs %}' '{% for l in langs %}{{ l.code }}: {{ l.name }}/' '{{ l.name_local }} bidi={{ l.bidi }}; {% endfor %}'}) def test_i18n31(self): output = self.engine.render_to_string('i18n31', {'langcodes': (('sl', 'Slovenian'), ('fa', 'Persian'))}) self.assertEqual( output, 'sl: Slovenian/Sloven\u0161\u010dina bidi=False; ' 'fa: Persian/\u0641\u0627\u0631\u0633\u06cc bidi=True; ' ) @setup({'i18n32': '{% load i18n %}{{ "hu"|language_name }} ' '{{ "hu"|language_name_local }} {{ "hu"|language_bidi }}'}) def test_i18n32(self): output = self.engine.render_to_string('i18n32') self.assertEqual(output, 'Hungarian Magyar False') @setup({'i18n33': '{% load i18n %}' '{{ langcode|language_name }} {{ langcode|language_name_local }} ' '{{ langcode|language_bidi }}'}) def test_i18n33(self): output = self.engine.render_to_string('i18n33', {'langcode': 'nl'}) self.assertEqual(output, 'Dutch Nederlands False') # blocktrans handling of variables which are not in the context. # this should work as if blocktrans was not there (#19915) @setup({'i18n34': '{% load i18n %}{% blocktrans %}{{ missing }}{% endblocktrans %}'}) def test_i18n34(self): output = self.engine.render_to_string('i18n34') if self.engine.string_if_invalid: self.assertEqual(output, 'INVALID') else: self.assertEqual(output, '') @setup({'i18n34_2': '{% load i18n %}{% blocktrans with a=\'α\' %}{{ missing }}{% endblocktrans %}'}) def test_i18n34_2(self): output = self.engine.render_to_string('i18n34_2') if self.engine.string_if_invalid: self.assertEqual(output, 'INVALID') else: self.assertEqual(output, '') @setup({'i18n34_3': '{% load i18n %}{% blocktrans with a=anton %}{{ missing }}{% endblocktrans %}'}) def test_i18n34_3(self): output = self.engine.render_to_string('i18n34_3', {'anton': '\xce\xb1'}) if self.engine.string_if_invalid: self.assertEqual(output, 'INVALID') else: self.assertEqual(output, '') # trans tag with as var @setup({'i18n35': '{% load i18n %}{% trans "Page not found" as page_not_found %}{{ page_not_found }}'}) def test_i18n35(self): with translation.override('de'): output = self.engine.render_to_string('i18n35') self.assertEqual(output, 'Seite nicht gefunden') @setup({'i18n36': '{% load i18n %}' '{% trans "Page not found" noop as page_not_found %}{{ page_not_found }}'}) def test_i18n36(self): with translation.override('de'): output = self.engine.render_to_string('i18n36') self.assertEqual(output, 'Page not found') @setup({'i18n37': '{% load i18n %}' '{% trans "Page not found" as page_not_found %}' '{% blocktrans %}Error: {{ page_not_found }}{% endblocktrans %}'}) def test_i18n37(self): with translation.override('de'): output = self.engine.render_to_string('i18n37') self.assertEqual(output, 'Error: Seite nicht gefunden') # Test whitespace in filter arguments @setup({'i18n38': '{% load i18n custom %}' '{% get_language_info for "de"|noop:"x y" as l %}' '{{ l.code }}: {{ l.name }}/{{ l.name_local }} bidi={{ l.bidi }}'}) def test_i18n38(self): output = self.engine.render_to_string('i18n38') self.assertEqual(output, 'de: German/Deutsch bidi=False') @setup({'i18n38_2': '{% load i18n custom %}' '{% get_language_info_list for langcodes|noop:"x y" as langs %}' '{% for l in langs %}{{ l.code }}: {{ l.name }}/' '{{ l.name_local }} bidi={{ l.bidi }}; {% endfor %}'}) def test_i18n38_2(self): output = self.engine.render_to_string('i18n38_2', {'langcodes': ['it', 'no']}) self.assertEqual(output, 'it: Italian/italiano bidi=False; no: Norwegian/norsk bidi=False; ')
{"/home/admin.py": ["/home/models.py"], "/need_install/Django-1.8.17/tests/fixtures_migration/tests.py": ["/need_install/Django-1.8.17/tests/fixtures_migration/models.py"], "/home/views.py": ["/home/models.py"]}
45,239
MulticsYin/MulticsSH
refs/heads/master
/need_install/Django-1.8.17/tests/gis_tests/maps/tests.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from unittest import skipUnless from django.contrib.gis.geos import HAS_GEOS from django.test import TestCase from django.test.utils import modify_settings, override_settings from django.utils.encoding import force_text GOOGLE_MAPS_API_KEY = 'XXXX' @skipUnless(HAS_GEOS, 'Geos is required.') @modify_settings( INSTALLED_APPS={'append': 'django.contrib.gis'}, ) class GoogleMapsTest(TestCase): @override_settings(GOOGLE_MAPS_API_KEY=GOOGLE_MAPS_API_KEY) def test_google_map_scripts(self): """ Testing GoogleMap.scripts() output. See #20773. """ from django.contrib.gis.maps.google.gmap import GoogleMap google_map = GoogleMap() scripts = google_map.scripts self.assertIn(GOOGLE_MAPS_API_KEY, scripts) self.assertIn("new GMap2", scripts) @override_settings(GOOGLE_MAPS_API_KEY=GOOGLE_MAPS_API_KEY) def test_unicode_in_google_maps(self): """ Test that GoogleMap doesn't crash with non-ASCII content. """ from django.contrib.gis.geos import Point from django.contrib.gis.maps.google.gmap import GoogleMap, GMarker center = Point(6.146805, 46.227574) marker = GMarker(center, title='En français !') google_map = GoogleMap(center=center, zoom=18, markers=[marker]) self.assertIn("En français", google_map.scripts) def test_gevent_html_safe(self): from django.contrib.gis.maps.google.overlays import GEvent event = GEvent('click', 'function() {location.href = "http://www.google.com"}') self.assertTrue(hasattr(GEvent, '__html__')) self.assertEqual(force_text(event), event.__html__()) def test_goverlay_html_safe(self): from django.contrib.gis.maps.google.overlays import GOverlayBase overlay = GOverlayBase() overlay.js_params = '"foo", "bar"' self.assertTrue(hasattr(GOverlayBase, '__html__')) self.assertEqual(force_text(overlay), overlay.__html__())
{"/home/admin.py": ["/home/models.py"], "/need_install/Django-1.8.17/tests/fixtures_migration/tests.py": ["/need_install/Django-1.8.17/tests/fixtures_migration/models.py"], "/home/views.py": ["/home/models.py"]}
45,240
MulticsYin/MulticsSH
refs/heads/master
/need_install/Django-1.8.17/tests/servers/test_basehttp.py
from django.core.handlers.wsgi import WSGIRequest from django.core.servers.basehttp import WSGIRequestHandler from django.test import TestCase from django.test.client import RequestFactory from django.test.utils import captured_stderr from django.utils.six import BytesIO class Stub(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) class WSGIRequestHandlerTestCase(TestCase): def test_log_message(self): request = WSGIRequest(RequestFactory().get('/').environ) request.makefile = lambda *args, **kwargs: BytesIO() handler = WSGIRequestHandler(request, '192.168.0.2', None) with captured_stderr() as stderr: handler.log_message('GET %s %s', 'A', 'B') self.assertIn('] GET A B', stderr.getvalue()) def test_https(self): request = WSGIRequest(RequestFactory().get('/').environ) request.makefile = lambda *args, **kwargs: BytesIO() handler = WSGIRequestHandler(request, '192.168.0.2', None) with captured_stderr() as stderr: handler.log_message("GET %s %s", str('\x16\x03'), "4") self.assertIn( "You're accessing the development server over HTTPS, " "but it only supports HTTP.", stderr.getvalue() ) def test_strips_underscore_headers(self): """WSGIRequestHandler ignores headers containing underscores. This follows the lead of nginx and Apache 2.4, and is to avoid ambiguity between dashes and underscores in mapping to WSGI environ, which can have security implications. """ def test_app(environ, start_response): """A WSGI app that just reflects its HTTP environ.""" start_response('200 OK', []) http_environ_items = sorted( '%s:%s' % (k, v) for k, v in environ.items() if k.startswith('HTTP_') ) yield (','.join(http_environ_items)).encode('utf-8') rfile = BytesIO() rfile.write(b"GET / HTTP/1.0\r\n") rfile.write(b"Some-Header: good\r\n") rfile.write(b"Some_Header: bad\r\n") rfile.write(b"Other_Header: bad\r\n") rfile.seek(0) # WSGIRequestHandler closes the output file; we need to make this a # no-op so we can still read its contents. class UnclosableBytesIO(BytesIO): def close(self): pass wfile = UnclosableBytesIO() def makefile(mode, *a, **kw): if mode == 'rb': return rfile elif mode == 'wb': return wfile request = Stub(makefile=makefile) server = Stub(base_environ={}, get_app=lambda: test_app) # We don't need to check stderr, but we don't want it in test output with captured_stderr(): # instantiating a handler runs the request as side effect WSGIRequestHandler(request, '192.168.0.2', server) wfile.seek(0) body = list(wfile.readlines())[-1] self.assertEqual(body, b'HTTP_SOME_HEADER:good')
{"/home/admin.py": ["/home/models.py"], "/need_install/Django-1.8.17/tests/fixtures_migration/tests.py": ["/need_install/Django-1.8.17/tests/fixtures_migration/models.py"], "/home/views.py": ["/home/models.py"]}
45,241
MulticsYin/MulticsSH
refs/heads/master
/need_install/Django-1.8.17/tests/template_backends/test_jinja2.py
# Since this package contains a "jinja2" directory, this is required to # silence an ImportWarning warning on Python 2. from __future__ import absolute_import import sys from unittest import skipIf from .test_dummy import TemplateStringsTests # Jinja2 doesn't run on Python 3.2 because it uses u-prefixed unicode strings. if sys.version_info[:2] == (2, 7) or sys.version_info[:2] >= (3, 3): try: import jinja2 except ImportError: jinja2 = None Jinja2 = None else: from django.template.backends.jinja2 import Jinja2 else: jinja2 = None Jinja2 = None @skipIf(jinja2 is None, "this test requires jinja2") class Jinja2Tests(TemplateStringsTests): engine_class = Jinja2 backend_name = 'jinja2' options = {'keep_trailing_newline': True} def test_self_context(self): """ Using 'self' in the context should not throw errors (#24538). """ # self will be overridden to be a TemplateReference, so the self # variable will not come through. Attempting to use one though should # not throw an error. template = self.engine.from_string('hello {{ foo }}!') content = template.render(context={'self': 'self', 'foo': 'world'}) self.assertEqual(content, 'hello world!')
{"/home/admin.py": ["/home/models.py"], "/need_install/Django-1.8.17/tests/fixtures_migration/tests.py": ["/need_install/Django-1.8.17/tests/fixtures_migration/models.py"], "/home/views.py": ["/home/models.py"]}
45,242
MulticsYin/MulticsSH
refs/heads/master
/need_install/Django-1.8.17/tests/known_related_objects/tests.py
from __future__ import unicode_literals from django.test import TestCase from .models import Organiser, Pool, PoolStyle, Tournament class ExistingRelatedInstancesTests(TestCase): fixtures = ['tournament.json'] def test_foreign_key(self): with self.assertNumQueries(2): tournament = Tournament.objects.get(pk=1) pool = tournament.pool_set.all()[0] self.assertIs(tournament, pool.tournament) def test_foreign_key_prefetch_related(self): with self.assertNumQueries(2): tournament = (Tournament.objects.prefetch_related('pool_set').get(pk=1)) pool = tournament.pool_set.all()[0] self.assertIs(tournament, pool.tournament) def test_foreign_key_multiple_prefetch(self): with self.assertNumQueries(2): tournaments = list(Tournament.objects.prefetch_related('pool_set').order_by('pk')) pool1 = tournaments[0].pool_set.all()[0] self.assertIs(tournaments[0], pool1.tournament) pool2 = tournaments[1].pool_set.all()[0] self.assertIs(tournaments[1], pool2.tournament) def test_queryset_or(self): tournament_1 = Tournament.objects.get(pk=1) tournament_2 = Tournament.objects.get(pk=2) with self.assertNumQueries(1): pools = tournament_1.pool_set.all() | tournament_2.pool_set.all() related_objects = set(pool.tournament for pool in pools) self.assertEqual(related_objects, {tournament_1, tournament_2}) def test_queryset_or_different_cached_items(self): tournament = Tournament.objects.get(pk=1) organiser = Organiser.objects.get(pk=1) with self.assertNumQueries(1): pools = tournament.pool_set.all() | organiser.pool_set.all() first = pools.filter(pk=1)[0] self.assertIs(first.tournament, tournament) self.assertIs(first.organiser, organiser) def test_queryset_or_only_one_with_precache(self): tournament_1 = Tournament.objects.get(pk=1) tournament_2 = Tournament.objects.get(pk=2) # 2 queries here as pool id 3 has tournament 2, which is not cached with self.assertNumQueries(2): pools = tournament_1.pool_set.all() | Pool.objects.filter(pk=3) related_objects = set(pool.tournament for pool in pools) self.assertEqual(related_objects, {tournament_1, tournament_2}) # and the other direction with self.assertNumQueries(2): pools = Pool.objects.filter(pk=3) | tournament_1.pool_set.all() related_objects = set(pool.tournament for pool in pools) self.assertEqual(related_objects, {tournament_1, tournament_2}) def test_queryset_and(self): tournament = Tournament.objects.get(pk=1) organiser = Organiser.objects.get(pk=1) with self.assertNumQueries(1): pools = tournament.pool_set.all() & organiser.pool_set.all() first = pools.filter(pk=1)[0] self.assertIs(first.tournament, tournament) self.assertIs(first.organiser, organiser) def test_one_to_one(self): with self.assertNumQueries(2): style = PoolStyle.objects.get(pk=1) pool = style.pool self.assertIs(style, pool.poolstyle) def test_one_to_one_select_related(self): with self.assertNumQueries(1): style = PoolStyle.objects.select_related('pool').get(pk=1) pool = style.pool self.assertIs(style, pool.poolstyle) def test_one_to_one_multi_select_related(self): with self.assertNumQueries(1): poolstyles = list(PoolStyle.objects.select_related('pool').order_by('pk')) self.assertIs(poolstyles[0], poolstyles[0].pool.poolstyle) self.assertIs(poolstyles[1], poolstyles[1].pool.poolstyle) def test_one_to_one_prefetch_related(self): with self.assertNumQueries(2): style = PoolStyle.objects.prefetch_related('pool').get(pk=1) pool = style.pool self.assertIs(style, pool.poolstyle) def test_one_to_one_multi_prefetch_related(self): with self.assertNumQueries(2): poolstyles = list(PoolStyle.objects.prefetch_related('pool').order_by('pk')) self.assertIs(poolstyles[0], poolstyles[0].pool.poolstyle) self.assertIs(poolstyles[1], poolstyles[1].pool.poolstyle) def test_reverse_one_to_one(self): with self.assertNumQueries(2): pool = Pool.objects.get(pk=2) style = pool.poolstyle self.assertIs(pool, style.pool) def test_reverse_one_to_one_select_related(self): with self.assertNumQueries(1): pool = Pool.objects.select_related('poolstyle').get(pk=2) style = pool.poolstyle self.assertIs(pool, style.pool) def test_reverse_one_to_one_prefetch_related(self): with self.assertNumQueries(2): pool = Pool.objects.prefetch_related('poolstyle').get(pk=2) style = pool.poolstyle self.assertIs(pool, style.pool) def test_reverse_one_to_one_multi_select_related(self): with self.assertNumQueries(1): pools = list(Pool.objects.select_related('poolstyle').order_by('pk')) self.assertIs(pools[1], pools[1].poolstyle.pool) self.assertIs(pools[2], pools[2].poolstyle.pool) def test_reverse_one_to_one_multi_prefetch_related(self): with self.assertNumQueries(2): pools = list(Pool.objects.prefetch_related('poolstyle').order_by('pk')) self.assertIs(pools[1], pools[1].poolstyle.pool) self.assertIs(pools[2], pools[2].poolstyle.pool)
{"/home/admin.py": ["/home/models.py"], "/need_install/Django-1.8.17/tests/fixtures_migration/tests.py": ["/need_install/Django-1.8.17/tests/fixtures_migration/models.py"], "/home/views.py": ["/home/models.py"]}
45,243
MulticsYin/MulticsSH
refs/heads/master
/need_install/Django-1.8.17/tests/migrations/test_base.py
import os from django.db import connection from django.db.migrations.recorder import MigrationRecorder from django.test import TransactionTestCase from django.utils._os import upath class MigrationTestBase(TransactionTestCase): """ Contains an extended set of asserts for testing migrations and schema operations. """ available_apps = ["migrations"] test_dir = os.path.abspath(os.path.dirname(upath(__file__))) def tearDown(self): # Reset applied-migrations state. recorder = MigrationRecorder(connection) recorder.migration_qs.filter(app='migrations').delete() def get_table_description(self, table): with connection.cursor() as cursor: return connection.introspection.get_table_description(cursor, table) def assertTableExists(self, table): with connection.cursor() as cursor: self.assertIn(table, connection.introspection.table_names(cursor)) def assertTableNotExists(self, table): with connection.cursor() as cursor: self.assertNotIn(table, connection.introspection.table_names(cursor)) def assertColumnExists(self, table, column): self.assertIn(column, [c.name for c in self.get_table_description(table)]) def assertColumnNotExists(self, table, column): self.assertNotIn(column, [c.name for c in self.get_table_description(table)]) def assertColumnNull(self, table, column): self.assertEqual([c.null_ok for c in self.get_table_description(table) if c.name == column][0], True) def assertColumnNotNull(self, table, column): self.assertEqual([c.null_ok for c in self.get_table_description(table) if c.name == column][0], False) def assertIndexExists(self, table, columns, value=True): with connection.cursor() as cursor: self.assertEqual( value, any( c["index"] for c in connection.introspection.get_constraints(cursor, table).values() if c['columns'] == list(columns) ), ) def assertIndexNotExists(self, table, columns): return self.assertIndexExists(table, columns, False) def assertFKExists(self, table, columns, to, value=True): with connection.cursor() as cursor: self.assertEqual( value, any( c["foreign_key"] == to for c in connection.introspection.get_constraints(cursor, table).values() if c['columns'] == list(columns) ), ) def assertFKNotExists(self, table, columns, to, value=True): return self.assertFKExists(table, columns, to, False)
{"/home/admin.py": ["/home/models.py"], "/need_install/Django-1.8.17/tests/fixtures_migration/tests.py": ["/need_install/Django-1.8.17/tests/fixtures_migration/models.py"], "/home/views.py": ["/home/models.py"]}
45,244
MulticsYin/MulticsSH
refs/heads/master
/need_install/Django-1.8.17/tests/template_backends/test_django.py
from template_tests.test_response import test_processor_name from django.template import RequestContext from django.template.backends.django import DjangoTemplates from django.test import RequestFactory, ignore_warnings from django.utils.deprecation import RemovedInDjango110Warning from .test_dummy import TemplateStringsTests class DjangoTemplatesTests(TemplateStringsTests): engine_class = DjangoTemplates backend_name = 'django' def test_context_has_priority_over_template_context_processors(self): # See ticket #23789. engine = DjangoTemplates({ 'DIRS': [], 'APP_DIRS': False, 'NAME': 'django', 'OPTIONS': { 'context_processors': [test_processor_name], }, }) template = engine.from_string('{{ processors }}') request = RequestFactory().get('/') # Check that context processors run content = template.render({}, request) self.assertEqual(content, 'yes') # Check that context overrides context processors content = template.render({'processors': 'no'}, request) self.assertEqual(content, 'no') @ignore_warnings(category=RemovedInDjango110Warning) def test_request_context_conflicts_with_request(self): template = self.engine.from_string('hello') request = RequestFactory().get('/') request_context = RequestContext(request) # This doesn't raise an exception. template.render(request_context, request) other_request = RequestFactory().get('/') msg = ("render() was called with a RequestContext and a request " "argument which refer to different requests. Make sure " "that the context argument is a dict or at least that " "the two arguments refer to the same request.") with self.assertRaisesMessage(ValueError, msg): template.render(request_context, other_request)
{"/home/admin.py": ["/home/models.py"], "/need_install/Django-1.8.17/tests/fixtures_migration/tests.py": ["/need_install/Django-1.8.17/tests/fixtures_migration/models.py"], "/home/views.py": ["/home/models.py"]}
45,245
MulticsYin/MulticsSH
refs/heads/master
/SmartHome/urls.py
# _*_ coding: utf-8 _*_ """SmartHome URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/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. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin from django.views.generic.base import RedirectView from DjangoUeditor import urls as DjangoUeditor_urls #use Django server /media/ files from django.conf import settings from home import views # 定义添加各接口的URL。 urlpatterns = [ # 定义后台URLhttp://127.0.0.1:8000/admin url(r'^admin/', include(admin.site.urls)), # 此为使用插件优化输入文本框所添加的。 url(r'^ueditor/', include(DjangoUeditor_urls)), # 定义主界面的URL,由于不涉及前端开发,故只有相应的接口。 url(r'^$',views.index,name = 'index'), # 定义URL获取用户的详细信息:http://127.0.0.1:8000/sh_user/<user_id> url(r'^sh_user/(?P<sh_id>[^/]+)/$',views.sh_user,name = 'sh_user'), # 定义获取用户令牌的RUL:http://127.0.0.1:8000/sh_user_token/<user_id> url(r'^sh_user_token/(?P<sh_user_id>[^/]+)/$',views.sh_user_token,name = 'sh_user_token'), # 定义获取设备信息的URL:http://127.0.0.1:8000/sh_device/<device_id> url(r'^sh_device/(?P<sh_id>[^/]+)/$',views.sh_device,name = 'sh_device'), # 定义获取传感器信息的接口:http://127.0.0.1:8000/sh_sensor/<device_id> url(r'^sh_sensor/(?P<sh_id>[^/]+)/$',views.sh_sensor,name = 'sh_sensor'), # 定义获取传感器类型的接口:http://127.0.0.1:8000/sh_sensor_typer/<device_id> url(r'^sh_sensor_type/(?P<sh_id>[^/]+)/$',views.sh_sensor_type,name = 'sh_sensor_type'), # 定义数据点的接口:http://127.0.0.1:8000/sh_datapoint_list/<sensor_id> url(r'^sh_datapoint_list/(?P<sh_id>[^/]+)/$',views.sh_datapoint_list,name = 'sh_datapoint_list'), ] # 添加文本框优化时添加的设置。 if settings.DEBUG: from django.conf.urls.static import static urlpatterns += static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
{"/home/admin.py": ["/home/models.py"], "/need_install/Django-1.8.17/tests/fixtures_migration/tests.py": ["/need_install/Django-1.8.17/tests/fixtures_migration/models.py"], "/home/views.py": ["/home/models.py"]}
45,246
MulticsYin/MulticsSH
refs/heads/master
/need_install/Django-1.8.17/tests/model_regress/test_pickle.py
import datetime import os import pickle import subprocess import sys from django.core.files.temp import NamedTemporaryFile from django.db import DJANGO_VERSION_PICKLE_KEY, models from django.test import TestCase, mock from django.utils._os import npath, upath from django.utils.version import get_version from .models import Article class ModelPickleTestCase(TestCase): def test_missing_django_version_unpickling(self): """ #21430 -- Verifies a warning is raised for models that are unpickled without a Django version """ class MissingDjangoVersion(models.Model): title = models.CharField(max_length=10) def __reduce__(self): reduce_list = super(MissingDjangoVersion, self).__reduce__() data = reduce_list[-1] del data[DJANGO_VERSION_PICKLE_KEY] return reduce_list p = MissingDjangoVersion(title="FooBar") msg = "Pickled model instance's Django version is not specified." with self.assertRaisesMessage(RuntimeWarning, msg): pickle.loads(pickle.dumps(p)) def test_unsupported_unpickle(self): """ #21430 -- Verifies a warning is raised for models that are unpickled with a different Django version than the current """ class DifferentDjangoVersion(models.Model): title = models.CharField(max_length=10) def __reduce__(self): reduce_list = super(DifferentDjangoVersion, self).__reduce__() data = reduce_list[-1] data[DJANGO_VERSION_PICKLE_KEY] = '1.0' return reduce_list p = DifferentDjangoVersion(title="FooBar") msg = "Pickled model instance's Django version 1.0 does not match the current version %s." % get_version() with self.assertRaisesMessage(RuntimeWarning, msg): pickle.loads(pickle.dumps(p)) def test_unpickling_when_appregistrynotready(self): """ #24007 -- Verifies that a pickled model can be unpickled without having to manually setup the apps registry beforehand. """ script_template = """#!/usr/bin/env python import pickle from django.conf import settings data = %r settings.configure(DEBUG=False, INSTALLED_APPS=('model_regress',), SECRET_KEY = "blah") article = pickle.loads(data) print(article.headline)""" a = Article.objects.create( headline="Some object", pub_date=datetime.datetime.now(), article_text="This is an article", ) with NamedTemporaryFile(mode='w+', suffix=".py") as script: script.write(script_template % pickle.dumps(a)) script.flush() # A path to model_regress must be set in PYTHONPATH model_regress_dir = os.path.dirname(upath(__file__)) model_regress_path = os.path.abspath(model_regress_dir) tests_path = os.path.split(model_regress_path)[0] pythonpath = os.environ.get('PYTHONPATH', '') pythonpath = npath(os.pathsep.join([tests_path, pythonpath])) with mock.patch.dict('os.environ', {'PYTHONPATH': pythonpath}): try: result = subprocess.check_output([sys.executable, script.name]) except subprocess.CalledProcessError: self.fail("Unable to reload model pickled data") self.assertEqual(result.strip().decode(), "Some object")
{"/home/admin.py": ["/home/models.py"], "/need_install/Django-1.8.17/tests/fixtures_migration/tests.py": ["/need_install/Django-1.8.17/tests/fixtures_migration/models.py"], "/home/views.py": ["/home/models.py"]}
45,247
MulticsYin/MulticsSH
refs/heads/master
/need_install/Django-1.8.17/tests/urlpatterns_reverse/included_namespace_urls.py
import warnings from django.conf.urls import include, patterns, url from django.utils.deprecation import RemovedInDjango110Warning from .namespace_urls import URLObject from .views import view_class_instance testobj3 = URLObject('testapp', 'test-ns3') # test deprecated patterns() function. convert to list of urls() in Django 1.10 with warnings.catch_warnings(): warnings.filterwarnings('ignore', category=RemovedInDjango110Warning) urlpatterns = patterns('urlpatterns_reverse.views', url(r'^normal/$', 'empty_view', name='inc-normal-view'), url(r'^normal/(?P<arg1>[0-9]+)/(?P<arg2>[0-9]+)/$', 'empty_view', name='inc-normal-view'), url(r'^\+\\\$\*/$', 'empty_view', name='inc-special-view'), url(r'^mixed_args/([0-9]+)/(?P<arg2>[0-9]+)/$', 'empty_view', name='inc-mixed-args'), url(r'^no_kwargs/([0-9]+)/([0-9]+)/$', 'empty_view', name='inc-no-kwargs'), url(r'^view_class/(?P<arg1>[0-9]+)/(?P<arg2>[0-9]+)/$', view_class_instance, name='inc-view-class'), (r'^test3/', include(testobj3.urls)), (r'^ns-included3/', include('urlpatterns_reverse.included_urls', namespace='inc-ns3')), (r'^ns-included4/', include('urlpatterns_reverse.namespace_urls', namespace='inc-ns4')), )
{"/home/admin.py": ["/home/models.py"], "/need_install/Django-1.8.17/tests/fixtures_migration/tests.py": ["/need_install/Django-1.8.17/tests/fixtures_migration/models.py"], "/home/views.py": ["/home/models.py"]}
45,248
MulticsYin/MulticsSH
refs/heads/master
/need_install/Django-1.8.17/tests/admin_validation/tests.py
from __future__ import unicode_literals from django import forms from django.contrib import admin from django.core.exceptions import ImproperlyConfigured from django.test import TestCase, ignore_warnings from django.test.utils import str_prefix from django.utils.deprecation import RemovedInDjango19Warning from .models import Album, Book, City, Song, TwoAlbumFKAndAnE class SongForm(forms.ModelForm): pass class ValidFields(admin.ModelAdmin): form = SongForm fields = ['title'] class ValidFormFieldsets(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): class ExtraFieldForm(SongForm): name = forms.CharField(max_length=50) return ExtraFieldForm fieldsets = ( (None, { 'fields': ('name',), }), ) @ignore_warnings(category=RemovedInDjango19Warning) class ValidationTestCase(TestCase): def test_readonly_and_editable(self): class SongAdmin(admin.ModelAdmin): readonly_fields = ["original_release"] fieldsets = [ (None, { "fields": ["title", "original_release"], }), ] SongAdmin.validate(Song) def test_custom_modelforms_with_fields_fieldsets(self): """ # Regression test for #8027: custom ModelForms with fields/fieldsets """ ValidFields.validate(Song) def test_custom_get_form_with_fieldsets(self): """ Ensure that the fieldsets validation is skipped when the ModelAdmin.get_form() method is overridden. Refs #19445. """ ValidFormFieldsets.validate(Song) def test_exclude_values(self): """ Tests for basic validation of 'exclude' option values (#12689) """ class ExcludedFields1(admin.ModelAdmin): exclude = ('foo') self.assertRaisesMessage(ImproperlyConfigured, "'ExcludedFields1.exclude' must be a list or tuple.", ExcludedFields1.validate, Book) def test_exclude_duplicate_values(self): class ExcludedFields2(admin.ModelAdmin): exclude = ('name', 'name') self.assertRaisesMessage(ImproperlyConfigured, "There are duplicate field(s) in ExcludedFields2.exclude", ExcludedFields2.validate, Book) def test_exclude_in_inline(self): class ExcludedFieldsInline(admin.TabularInline): model = Song exclude = ('foo') class ExcludedFieldsAlbumAdmin(admin.ModelAdmin): model = Album inlines = [ExcludedFieldsInline] self.assertRaisesMessage(ImproperlyConfigured, "'ExcludedFieldsInline.exclude' must be a list or tuple.", ExcludedFieldsAlbumAdmin.validate, Album) def test_exclude_inline_model_admin(self): """ # Regression test for #9932 - exclude in InlineModelAdmin # should not contain the ForeignKey field used in ModelAdmin.model """ class SongInline(admin.StackedInline): model = Song exclude = ['album'] class AlbumAdmin(admin.ModelAdmin): model = Album inlines = [SongInline] self.assertRaisesMessage(ImproperlyConfigured, "SongInline cannot exclude the field 'album' - this is the foreign key to the parent model admin_validation.Album.", AlbumAdmin.validate, Album) def test_app_label_in_admin_validation(self): """ Regression test for #15669 - Include app label in admin validation messages """ class RawIdNonexistingAdmin(admin.ModelAdmin): raw_id_fields = ('nonexisting',) self.assertRaisesMessage(ImproperlyConfigured, "'RawIdNonexistingAdmin.raw_id_fields' refers to field 'nonexisting' that is missing from model 'admin_validation.Album'.", RawIdNonexistingAdmin.validate, Album) def test_fk_exclusion(self): """ Regression test for #11709 - when testing for fk excluding (when exclude is given) make sure fk_name is honored or things blow up when there is more than one fk to the parent model. """ class TwoAlbumFKAndAnEInline(admin.TabularInline): model = TwoAlbumFKAndAnE exclude = ("e",) fk_name = "album1" class MyAdmin(admin.ModelAdmin): inlines = [TwoAlbumFKAndAnEInline] MyAdmin.validate(Album) def test_inline_self_validation(self): class TwoAlbumFKAndAnEInline(admin.TabularInline): model = TwoAlbumFKAndAnE class MyAdmin(admin.ModelAdmin): inlines = [TwoAlbumFKAndAnEInline] self.assertRaisesMessage(ValueError, "'admin_validation.TwoAlbumFKAndAnE' has more than one ForeignKey to 'admin_validation.Album'.", MyAdmin.validate, Album) def test_inline_with_specified(self): class TwoAlbumFKAndAnEInline(admin.TabularInline): model = TwoAlbumFKAndAnE fk_name = "album1" class MyAdmin(admin.ModelAdmin): inlines = [TwoAlbumFKAndAnEInline] MyAdmin.validate(Album) def test_readonly(self): class SongAdmin(admin.ModelAdmin): readonly_fields = ("title",) SongAdmin.validate(Song) def test_readonly_on_method(self): def my_function(obj): pass class SongAdmin(admin.ModelAdmin): readonly_fields = (my_function,) SongAdmin.validate(Song) def test_readonly_on_modeladmin(self): class SongAdmin(admin.ModelAdmin): readonly_fields = ("readonly_method_on_modeladmin",) def readonly_method_on_modeladmin(self, obj): pass SongAdmin.validate(Song) def test_readonly_method_on_model(self): class SongAdmin(admin.ModelAdmin): readonly_fields = ("readonly_method_on_model",) SongAdmin.validate(Song) def test_nonexistent_field(self): class SongAdmin(admin.ModelAdmin): readonly_fields = ("title", "nonexistent") self.assertRaisesMessage(ImproperlyConfigured, str_prefix("SongAdmin.readonly_fields[1], %(_)s'nonexistent' is not a callable " "or an attribute of 'SongAdmin' or found in the model 'Song'."), SongAdmin.validate, Song) def test_nonexistent_field_on_inline(self): class CityInline(admin.TabularInline): model = City readonly_fields = ['i_dont_exist'] # Missing attribute self.assertRaisesMessage(ImproperlyConfigured, str_prefix("CityInline.readonly_fields[0], %(_)s'i_dont_exist' is not a callable " "or an attribute of 'CityInline' or found in the model 'City'."), CityInline.validate, City) def test_extra(self): class SongAdmin(admin.ModelAdmin): def awesome_song(self, instance): if instance.title == "Born to Run": return "Best Ever!" return "Status unknown." SongAdmin.validate(Song) def test_readonly_lambda(self): class SongAdmin(admin.ModelAdmin): readonly_fields = (lambda obj: "test",) SongAdmin.validate(Song) def test_graceful_m2m_fail(self): """ Regression test for #12203/#12237 - Fail more gracefully when a M2M field that specifies the 'through' option is included in the 'fields' or the 'fieldsets' ModelAdmin options. """ class BookAdmin(admin.ModelAdmin): fields = ['authors'] self.assertRaisesMessage(ImproperlyConfigured, "'BookAdmin.fields' can't include the ManyToManyField field 'authors' because 'authors' manually specifies a 'through' model.", BookAdmin.validate, Book) def test_cannot_include_through(self): class FieldsetBookAdmin(admin.ModelAdmin): fieldsets = ( ('Header 1', {'fields': ('name',)}), ('Header 2', {'fields': ('authors',)}), ) self.assertRaisesMessage(ImproperlyConfigured, "'FieldsetBookAdmin.fieldsets[1][1]['fields']' can't include the ManyToManyField field 'authors' because 'authors' manually specifies a 'through' model.", FieldsetBookAdmin.validate, Book) def test_nested_fields(self): class NestedFieldsAdmin(admin.ModelAdmin): fields = ('price', ('name', 'subtitle')) NestedFieldsAdmin.validate(Book) def test_nested_fieldsets(self): class NestedFieldsetAdmin(admin.ModelAdmin): fieldsets = ( ('Main', {'fields': ('price', ('name', 'subtitle'))}), ) NestedFieldsetAdmin.validate(Book) def test_explicit_through_override(self): """ Regression test for #12209 -- If the explicitly provided through model is specified as a string, the admin should still be able use Model.m2m_field.through """ class AuthorsInline(admin.TabularInline): model = Book.authors.through class BookAdmin(admin.ModelAdmin): inlines = [AuthorsInline] # If the through model is still a string (and hasn't been resolved to a model) # the validation will fail. BookAdmin.validate(Book) def test_non_model_fields(self): """ Regression for ensuring ModelAdmin.fields can contain non-model fields that broke with r11737 """ class SongForm(forms.ModelForm): extra_data = forms.CharField() class FieldsOnFormOnlyAdmin(admin.ModelAdmin): form = SongForm fields = ['title', 'extra_data'] FieldsOnFormOnlyAdmin.validate(Song) def test_non_model_first_field(self): """ Regression for ensuring ModelAdmin.field can handle first elem being a non-model field (test fix for UnboundLocalError introduced with r16225). """ class SongForm(forms.ModelForm): extra_data = forms.CharField() class Meta: model = Song fields = '__all__' class FieldsOnFormOnlyAdmin(admin.ModelAdmin): form = SongForm fields = ['extra_data', 'title'] FieldsOnFormOnlyAdmin.validate(Song)
{"/home/admin.py": ["/home/models.py"], "/need_install/Django-1.8.17/tests/fixtures_migration/tests.py": ["/need_install/Django-1.8.17/tests/fixtures_migration/models.py"], "/home/views.py": ["/home/models.py"]}
45,249
MulticsYin/MulticsSH
refs/heads/master
/need_install/Django-1.8.17/tests/fixtures_migration/tests.py
from django.core import management from django.test import TransactionTestCase from .models import Book class TestNoInitialDataLoading(TransactionTestCase): """ Apps with migrations should ignore initial data. This test can be removed in Django 1.9 when migrations become required and initial data is no longer supported. """ available_apps = ['fixtures_migration'] def test_migrate(self): self.assertQuerysetEqual(Book.objects.all(), []) management.call_command( 'migrate', verbosity=0, ) self.assertQuerysetEqual(Book.objects.all(), []) def test_flush(self): self.assertQuerysetEqual(Book.objects.all(), []) management.call_command( 'flush', verbosity=0, interactive=False, load_initial_data=False ) self.assertQuerysetEqual(Book.objects.all(), [])
{"/home/admin.py": ["/home/models.py"], "/need_install/Django-1.8.17/tests/fixtures_migration/tests.py": ["/need_install/Django-1.8.17/tests/fixtures_migration/models.py"], "/home/views.py": ["/home/models.py"]}
45,250
MulticsYin/MulticsSH
refs/heads/master
/need_install/Django-1.8.17/tests/view_tests/tests/test_defaults.py
from __future__ import unicode_literals from django.test import TestCase from django.test.utils import override_settings from ..models import UrlArticle @override_settings(ROOT_URLCONF='view_tests.urls') class DefaultsTests(TestCase): """Test django views in django/views/defaults.py""" fixtures = ['testdata.json'] non_existing_urls = ['/non_existing_url/', # this is in urls.py '/other_non_existing_url/'] # this NOT in urls.py def test_page_not_found(self): "A 404 status is returned by the page_not_found view" for url in self.non_existing_urls: response = self.client.get(url) self.assertEqual(response.status_code, 404) @override_settings(TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': { 'loaders': [ ('django.template.loaders.locmem.Loader', { '404.html': '{{ csrf_token }}', }), ], }, }]) def test_csrf_token_in_404(self): """ The 404 page should have the csrf_token available in the context """ # See ticket #14565 for url in self.non_existing_urls: response = self.client.get(url) self.assertNotEqual(response.content, 'NOTPROVIDED') self.assertNotEqual(response.content, '') def test_server_error(self): "The server_error view raises a 500 status" response = self.client.get('/server_error/') self.assertEqual(response.status_code, 500) @override_settings(TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': { 'loaders': [ ('django.template.loaders.locmem.Loader', { '404.html': 'This is a test template for a 404 error.', '500.html': 'This is a test template for a 500 error.', }), ], }, }]) def test_custom_templates(self): """ Test that 404.html and 500.html templates are picked by their respective handler. """ for code, url in ((404, '/non_existing_url/'), (500, '/server_error/')): response = self.client.get(url) self.assertContains(response, "test template for a %d error" % code, status_code=code) def test_get_absolute_url_attributes(self): "A model can set attributes on the get_absolute_url method" self.assertTrue(getattr(UrlArticle.get_absolute_url, 'purge', False), 'The attributes of the original get_absolute_url must be added.') article = UrlArticle.objects.get(pk=1) self.assertTrue(getattr(article.get_absolute_url, 'purge', False), 'The attributes of the original get_absolute_url must be added.') @override_settings(DEFAULT_CONTENT_TYPE="text/xml") def test_default_content_type_is_text_html(self): """ Content-Type of the default error responses is text/html. Refs #20822. """ response = self.client.get('/raises400/') self.assertEqual(response['Content-Type'], 'text/html') response = self.client.get('/raises403/') self.assertEqual(response['Content-Type'], 'text/html') response = self.client.get('/non_existing_url/') self.assertEqual(response['Content-Type'], 'text/html') response = self.client.get('/server_error/') self.assertEqual(response['Content-Type'], 'text/html')
{"/home/admin.py": ["/home/models.py"], "/need_install/Django-1.8.17/tests/fixtures_migration/tests.py": ["/need_install/Django-1.8.17/tests/fixtures_migration/models.py"], "/home/views.py": ["/home/models.py"]}
45,251
MulticsYin/MulticsSH
refs/heads/master
/need_install/Django-1.8.17/tests/db_functions/tests.py
from __future__ import unicode_literals from unittest import skipUnless from django.db import connection from django.db.models import CharField, TextField, Value as V from django.db.models.functions import ( Coalesce, Concat, ConcatPair, Length, Lower, Substr, Upper, ) from django.test import TestCase from django.utils import six, timezone from .models import Article, Author lorem_ipsum = """ Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.""" class FunctionTests(TestCase): def test_coalesce(self): Author.objects.create(name='John Smith', alias='smithj') Author.objects.create(name='Rhonda') authors = Author.objects.annotate(display_name=Coalesce('alias', 'name')) self.assertQuerysetEqual( authors.order_by('name'), [ 'smithj', 'Rhonda', ], lambda a: a.display_name ) with self.assertRaisesMessage(ValueError, 'Coalesce must take at least two expressions'): Author.objects.annotate(display_name=Coalesce('alias')) def test_coalesce_mixed_values(self): a1 = Author.objects.create(name='John Smith', alias='smithj') a2 = Author.objects.create(name='Rhonda') ar1 = Article.objects.create( title="How to Django", text=lorem_ipsum, written=timezone.now(), ) ar1.authors.add(a1) ar1.authors.add(a2) # mixed Text and Char article = Article.objects.annotate( headline=Coalesce('summary', 'text', output_field=TextField()), ) self.assertQuerysetEqual( article.order_by('title'), [ lorem_ipsum, ], lambda a: a.headline ) # mixed Text and Char wrapped article = Article.objects.annotate( headline=Coalesce(Lower('summary'), Lower('text'), output_field=TextField()), ) self.assertQuerysetEqual( article.order_by('title'), [ lorem_ipsum.lower(), ], lambda a: a.headline ) def test_coalesce_ordering(self): Author.objects.create(name='John Smith', alias='smithj') Author.objects.create(name='Rhonda') authors = Author.objects.order_by(Coalesce('alias', 'name')) self.assertQuerysetEqual( authors, [ 'Rhonda', 'John Smith', ], lambda a: a.name ) authors = Author.objects.order_by(Coalesce('alias', 'name').asc()) self.assertQuerysetEqual( authors, [ 'Rhonda', 'John Smith', ], lambda a: a.name ) authors = Author.objects.order_by(Coalesce('alias', 'name').desc()) self.assertQuerysetEqual( authors, [ 'John Smith', 'Rhonda', ], lambda a: a.name ) def test_concat(self): Author.objects.create(name='Jayden') Author.objects.create(name='John Smith', alias='smithj', goes_by='John') Author.objects.create(name='Margaret', goes_by='Maggie') Author.objects.create(name='Rhonda', alias='adnohR') authors = Author.objects.annotate(joined=Concat('alias', 'goes_by')) self.assertQuerysetEqual( authors.order_by('name'), [ '', 'smithjJohn', 'Maggie', 'adnohR', ], lambda a: a.joined ) with self.assertRaisesMessage(ValueError, 'Concat must take at least two expressions'): Author.objects.annotate(joined=Concat('alias')) def test_concat_many(self): Author.objects.create(name='Jayden') Author.objects.create(name='John Smith', alias='smithj', goes_by='John') Author.objects.create(name='Margaret', goes_by='Maggie') Author.objects.create(name='Rhonda', alias='adnohR') authors = Author.objects.annotate( joined=Concat('name', V(' ('), 'goes_by', V(')'), output_field=CharField()), ) self.assertQuerysetEqual( authors.order_by('name'), [ 'Jayden ()', 'John Smith (John)', 'Margaret (Maggie)', 'Rhonda ()', ], lambda a: a.joined ) def test_concat_mixed_char_text(self): Article.objects.create(title='The Title', text=lorem_ipsum, written=timezone.now()) article = Article.objects.annotate( title_text=Concat('title', V(' - '), 'text', output_field=TextField()), ).get(title='The Title') self.assertEqual(article.title + ' - ' + article.text, article.title_text) # wrap the concat in something else to ensure that we're still # getting text rather than bytes article = Article.objects.annotate( title_text=Upper(Concat('title', V(' - '), 'text', output_field=TextField())), ).get(title='The Title') expected = article.title + ' - ' + article.text self.assertEqual(expected.upper(), article.title_text) @skipUnless(connection.vendor == 'sqlite', "sqlite specific implementation detail.") def test_concat_coalesce_idempotent(self): pair = ConcatPair(V('a'), V('b')) # Check nodes counts self.assertEqual(len(list(pair.flatten())), 3) self.assertEqual(len(list(pair.coalesce().flatten())), 7) # + 2 Coalesce + 2 Value() self.assertEqual(len(list(pair.flatten())), 3) def test_concat_sql_generation_idempotency(self): qs = Article.objects.annotate(description=Concat('title', V(': '), 'summary')) # Multiple compilations should not alter the generated query. self.assertEqual(str(qs.query), str(qs.all().query)) def test_lower(self): Author.objects.create(name='John Smith', alias='smithj') Author.objects.create(name='Rhonda') authors = Author.objects.annotate(lower_name=Lower('name')) self.assertQuerysetEqual( authors.order_by('name'), [ 'john smith', 'rhonda', ], lambda a: a.lower_name ) Author.objects.update(name=Lower('name')) self.assertQuerysetEqual( authors.order_by('name'), [ ('john smith', 'john smith'), ('rhonda', 'rhonda'), ], lambda a: (a.lower_name, a.name) ) def test_upper(self): Author.objects.create(name='John Smith', alias='smithj') Author.objects.create(name='Rhonda') authors = Author.objects.annotate(upper_name=Upper('name')) self.assertQuerysetEqual( authors.order_by('name'), [ 'JOHN SMITH', 'RHONDA', ], lambda a: a.upper_name ) Author.objects.update(name=Upper('name')) self.assertQuerysetEqual( authors.order_by('name'), [ ('JOHN SMITH', 'JOHN SMITH'), ('RHONDA', 'RHONDA'), ], lambda a: (a.upper_name, a.name) ) def test_length(self): Author.objects.create(name='John Smith', alias='smithj') Author.objects.create(name='Rhonda') authors = Author.objects.annotate( name_length=Length('name'), alias_length=Length('alias')) self.assertQuerysetEqual( authors.order_by('name'), [ (10, 6), (6, None), ], lambda a: (a.name_length, a.alias_length) ) self.assertEqual(authors.filter(alias_length__lte=Length('name')).count(), 1) def test_length_ordering(self): Author.objects.create(name='John Smith', alias='smithj') Author.objects.create(name='John Smith', alias='smithj1') Author.objects.create(name='Rhonda', alias='ronny') authors = Author.objects.order_by(Length('name'), Length('alias')) self.assertQuerysetEqual( authors, [ ('Rhonda', 'ronny'), ('John Smith', 'smithj'), ('John Smith', 'smithj1'), ], lambda a: (a.name, a.alias) ) def test_substr(self): Author.objects.create(name='John Smith', alias='smithj') Author.objects.create(name='Rhonda') authors = Author.objects.annotate(name_part=Substr('name', 5, 3)) self.assertQuerysetEqual( authors.order_by('name'), [ ' Sm', 'da', ], lambda a: a.name_part ) authors = Author.objects.annotate(name_part=Substr('name', 2)) self.assertQuerysetEqual( authors.order_by('name'), [ 'ohn Smith', 'honda', ], lambda a: a.name_part ) # if alias is null, set to first 5 lower characters of the name Author.objects.filter(alias__isnull=True).update( alias=Lower(Substr('name', 1, 5)), ) self.assertQuerysetEqual( authors.order_by('name'), [ 'smithj', 'rhond', ], lambda a: a.alias ) def test_substr_start(self): Author.objects.create(name='John Smith', alias='smithj') a = Author.objects.annotate( name_part_1=Substr('name', 1), name_part_2=Substr('name', 2), ).get(alias='smithj') self.assertEqual(a.name_part_1[1:], a.name_part_2) with six.assertRaisesRegex(self, ValueError, "'pos' must be greater than 0"): Author.objects.annotate(raises=Substr('name', 0)) def test_substr_with_expressions(self): Author.objects.create(name='John Smith', alias='smithj') Author.objects.create(name='Rhonda') authors = Author.objects.annotate(name_part=Substr('name', 5, 3)) self.assertQuerysetEqual( authors.order_by('name'), [ ' Sm', 'da', ], lambda a: a.name_part ) def test_nested_function_ordering(self): Author.objects.create(name='John Smith') Author.objects.create(name='Rhonda Simpson', alias='ronny') authors = Author.objects.order_by(Length(Coalesce('alias', 'name'))) self.assertQuerysetEqual( authors, [ 'Rhonda Simpson', 'John Smith', ], lambda a: a.name ) authors = Author.objects.order_by(Length(Coalesce('alias', 'name')).desc()) self.assertQuerysetEqual( authors, [ 'John Smith', 'Rhonda Simpson', ], lambda a: a.name )
{"/home/admin.py": ["/home/models.py"], "/need_install/Django-1.8.17/tests/fixtures_migration/tests.py": ["/need_install/Django-1.8.17/tests/fixtures_migration/models.py"], "/home/views.py": ["/home/models.py"]}
45,252
MulticsYin/MulticsSH
refs/heads/master
/need_install/Django-1.8.17/tests/admin_scripts/management/commands/validation_command.py
from django.core.management.base import BaseCommand class InvalidCommand(BaseCommand): help = ("Test raising an error if both requires_system_checks " "and requires_model_validation are defined.") requires_system_checks = True requires_model_validation = True def handle(self, **options): pass
{"/home/admin.py": ["/home/models.py"], "/need_install/Django-1.8.17/tests/fixtures_migration/tests.py": ["/need_install/Django-1.8.17/tests/fixtures_migration/models.py"], "/home/views.py": ["/home/models.py"]}
45,253
MulticsYin/MulticsSH
refs/heads/master
/home/views.py
#_*_ coding:utf-8 _*_ # 为保证代码的简洁,添加模版文件。视图只用使用模型对应的模板文件,传入元组自动匹配 # 模板变量便可。模板文件在 ./templates/home from django.shortcuts import render from django.http import HttpResponse from .models import * from django.shortcuts import redirect # Create your views here. #主目录,本项目不涉及前端,故只保留一个接口而不进行开发。 def index(request): return HttpResponse(u'Welcome to gree Smart Home...') # 定义用户信息返回的函数。 def sh_user(request,sh_id): try: column = tb_user.objects.get(sh_id = sh_id) return render(request, 'home/sh_user.html', {'tb_user': column}) except tb_user.DoesNotExist: return HttpResponse(u'sh_user ID错误,请确认URL中ID号是否存在。。。') # 定义用户令牌返回的函数。 def sh_user_token(request,sh_user_id): try: column = tb_user_token.objects.get(sh_user_id = sh_user_id) return render(request, 'home/sh_user_token.html', {'tb_user_token': column}) except tb_user_token.DoesNotExist: return HttpResponse(u'sh_user_token ID错误,请确认URL中ID号是否存在。。。') # 定义设备信息返回的函数。 def sh_device(request,sh_id): try: column = tb_device.objects.get(sh_id = sh_id) return render(request, 'home/sh_device.html', {'tb_device': column}) except tb_device.DoesNotExist: return HttpResponse(u'sh_device ID错误,请确认URL中ID号是否存在。。。') # 定义传感器返回的函数。 def sh_sensor(request,sh_id): try: column = tb_sensor.objects.get(sh_id = sh_id) return render(request, 'home/sh_sensor.html', {'tb_sensor': column}) except tb_sensor.DoesNotExist: return HttpResponse(u'sh_sensor ID错误,请确认URL中ID号是否存在。。。') # 定义传感器返回类型的函数。 def sh_sensor_type(request,sh_id): try: column = tb_sensor_type.objects.get(sh_id = sh_id) return render(request, 'home/sh_sensor_type.html', {'tb_sensor_type': column}) except tb_sensor_type.DoesNotExist: return HttpResponse(u'sh_sensor_type ID错误,请确认URL中ID号是否存在。。。') # 定义数据点的返回函数。 def sh_datapoint_list(request,sh_id): try: column = tb_datapoint_list.objects.get(sh_id = sh_id) return render(request, 'home/sh_datapoint_list.html', {'tb_datapoint_list': column}) except tb_datapoint_list.DoesNotExist: return HttpResponse(u'sh_datapoint_list ID错误,请确认URL中ID号是否存在。。。')
{"/home/admin.py": ["/home/models.py"], "/need_install/Django-1.8.17/tests/fixtures_migration/tests.py": ["/need_install/Django-1.8.17/tests/fixtures_migration/models.py"], "/home/views.py": ["/home/models.py"]}
45,254
MulticsYin/MulticsSH
refs/heads/master
/need_install/Django-1.8.17/tests/admin_views/urls.py
from django.conf.urls import include, url from . import admin, custom_has_permission_admin, customadmin, views urlpatterns = [ url(r'^test_admin/admin/doc/', include('django.contrib.admindocs.urls')), url(r'^test_admin/admin/secure-view/$', views.secure_view, name='secure_view'), url(r'^test_admin/admin/', include(admin.site.urls)), url(r'^test_admin/admin2/', include(customadmin.site.urls)), url(r'^test_admin/admin3/', include(admin.site.get_urls(), 'admin3', 'admin'), dict(form_url='pony')), url(r'^test_admin/admin4/', include(customadmin.simple_site.urls)), url(r'^test_admin/admin5/', include(admin.site2.urls)), url(r'^test_admin/admin7/', include(admin.site7.urls)), url(r'^test_admin/has_permission_admin/', include(custom_has_permission_admin.site.urls)), ]
{"/home/admin.py": ["/home/models.py"], "/need_install/Django-1.8.17/tests/fixtures_migration/tests.py": ["/need_install/Django-1.8.17/tests/fixtures_migration/models.py"], "/home/views.py": ["/home/models.py"]}
45,255
MulticsYin/MulticsSH
refs/heads/master
/need_install/Django-1.8.17/tests/urlpatterns_reverse/erroneous_urls.py
import warnings from django.conf.urls import url from django.utils.deprecation import RemovedInDjango110Warning from . import views # Test deprecated behavior of passing strings as view to url(). # Some of these can be removed in Django 1.10 as they aren't convertable to # callables. with warnings.catch_warnings(): warnings.filterwarnings('ignore', category=RemovedInDjango110Warning) urlpatterns = [ # View has erroneous import url(r'erroneous_inner/$', views.erroneous_view), # Module has erroneous import url(r'erroneous_outer/$', 'urlpatterns_reverse.erroneous_views_module.erroneous_view'), # Module is an unqualified string url(r'erroneous_unqualified/$', 'unqualified_view'), # View does not exist url(r'missing_inner/$', 'urlpatterns_reverse.views.missing_view'), # View is not callable url(r'uncallable/$', 'urlpatterns_reverse.views.uncallable'), # Module does not exist url(r'missing_outer/$', 'urlpatterns_reverse.missing_module.missing_view'), # Regex contains an error (refs #6170) url(r'(regex_error/$', views.empty_view), ]
{"/home/admin.py": ["/home/models.py"], "/need_install/Django-1.8.17/tests/fixtures_migration/tests.py": ["/need_install/Django-1.8.17/tests/fixtures_migration/models.py"], "/home/views.py": ["/home/models.py"]}
45,256
MulticsYin/MulticsSH
refs/heads/master
/need_install/django-admin-bootstrap/bootstrap_admin/templatetags/bootstrap_admin_template_tags.py
from django.contrib.admin import site from django.apps import apps from django.utils.text import capfirst from django.core.urlresolvers import reverse, NoReverseMatch from django.core.exceptions import ImproperlyConfigured from django.utils import six from django.conf import settings from django import template from django import VERSION as DJANGO_VERSION # Depending on you python version, reduce has been moved to functools try: from functools import reduce except ImportError: pass register = template.Library() MAX_LENGTH_BOOTSTRAP_COLUMN = 12 def css_classes_for_field(field, custom_classes): orig_class = field.field.widget.attrs.get('class', '') required = 'required' if field.field.required else '' classes = field.css_classes(' '.join([orig_class, custom_classes, required])) return classes @register.filter() def get_label(field, custom_classes=''): classes = css_classes_for_field(field, custom_classes) return field.label_tag(attrs={'class': classes}, label_suffix='') @register.filter() def add_class(field, custom_classes=''): classes = css_classes_for_field(field, custom_classes) try: # For widgets like SelectMultiple, checkboxselectmultiple field.field.widget.widget.attrs.update({'class': classes}) except: field.field.widget.attrs.update({'class': classes}) return field @register.filter() def widget_type(field): if isinstance(field, dict): return 'adminreadonlyfield' try: # For widgets like SelectMultiple, checkboxselectmultiple widget_type = field.field.widget.widget.__class__.__name__.lower() except: widget_type = field.field.widget.__class__.__name__.lower() return widget_type @register.filter() def placeholder(field, placeholder=''): field.field.widget.attrs.update({'placeholder': placeholder}) return field def sidebar_menu_setting(): return getattr(settings, 'BOOTSTRAP_ADMIN_SIDEBAR_MENU', False) @register.assignment_tag def display_sidebar_menu(has_filters=False): if has_filters: # Always display the menu in change_list.html return True return sidebar_menu_setting() @register.assignment_tag def jquery_vendor_path(): if DJANGO_VERSION < (1, 9): return 'admin/js/jquery.js' return 'admin/js/vendor/jquery/jquery.js' @register.assignment_tag def datetime_widget_css_path(): if DJANGO_VERSION < (1, 9): return '' return 'admin/css/datetime_widget.css' @register.inclusion_tag('bootstrap_admin/sidebar_menu.html', takes_context=True) def render_menu_app_list(context): show_global_menu = sidebar_menu_setting() if not show_global_menu: return {'app_list': ''} if DJANGO_VERSION < (1, 8): dependencie = 'django.core.context_processors.request' processors = settings.TEMPLATE_CONTEXT_PROCESSORS dependency_str = 'settings.TEMPLATE_CONTEXT_PROCESSORS' else: dependencie = 'django.template.context_processors.request' implemented_engines = getattr(settings, 'BOOTSTRAP_ADMIN_ENGINES', ['django.template.backends.django.DjangoTemplates']) dependency_str = "the 'context_processors' 'OPTION' of one of the " + \ "following engines: %s" % implemented_engines filtered_engines = [engine for engine in settings.TEMPLATES if engine['BACKEND'] in implemented_engines] if len(filtered_engines) == 0: raise ImproperlyConfigured( "bootstrap_admin: No compatible template engine found" + "bootstrap_admin requires one of the following engines: %s" % implemented_engines ) processors = reduce(lambda x, y: x.extend(y), [ engine.get('OPTIONS', {}).get('context_processors', []) for engine in filtered_engines]) if dependencie not in processors: raise ImproperlyConfigured( "bootstrap_admin: in order to use the 'sidebar menu' requires" + " the '%s' to be added to %s" % (dependencie, dependency_str) ) # Code adapted from django.contrib.admin.AdminSite app_dict = {} user = context.get('user') for model, model_admin in site._registry.items(): app_label = model._meta.app_label has_module_perms = user.has_module_perms(app_label) if has_module_perms: perms = model_admin.get_model_perms(context.get('request')) # Check whether user has any perm for this module. # If so, add the module to the model_list. if True in perms.values(): info = (app_label, model._meta.model_name) model_dict = { 'name': capfirst(model._meta.verbose_name_plural), 'object_name': model._meta.object_name, 'perms': perms, } if perms.get('change', False): try: model_dict['admin_url'] = reverse( 'admin:%s_%s_changelist' % info, current_app=site.name ) except NoReverseMatch: pass if perms.get('add', False): try: model_dict['add_url'] = reverse( 'admin:%s_%s_add' % info, current_app=site.name ) except NoReverseMatch: pass if app_label in app_dict: app_dict[app_label]['models'].append(model_dict) else: app_dict[app_label] = { 'name': apps.get_app_config(app_label).verbose_name, 'app_label': app_label, 'app_url': reverse( 'admin:app_list', kwargs={'app_label': app_label}, current_app=site.name ), 'has_module_perms': has_module_perms, 'models': [model_dict], } # Sort the apps alphabetically. app_list = list(six.itervalues(app_dict)) app_list.sort(key=lambda x: x['name'].lower()) # Sort the models alphabetically within each sapp. for app in app_list: app['models'].sort(key=lambda x: x['name']) return {'app_list': app_list, 'current_url': context.get('request').path} @register.filter() def class_for_field_boxes(line): size_column = MAX_LENGTH_BOOTSTRAP_COLUMN // len(line.fields) return 'col-sm-{0}'.format(size_column or 1) # if '0' replace with 1
{"/home/admin.py": ["/home/models.py"], "/need_install/Django-1.8.17/tests/fixtures_migration/tests.py": ["/need_install/Django-1.8.17/tests/fixtures_migration/models.py"], "/home/views.py": ["/home/models.py"]}
45,257
MulticsYin/MulticsSH
refs/heads/master
/home/migrations/0001_initial.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import DjangoUeditor.models class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='tb_datapoint_list', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('sh_id', models.IntegerField(db_index=True)), ('sh_sensor_id', models.IntegerField()), ('sh_timestamp', models.IntegerField()), ('sh_value', DjangoUeditor.models.UEditorField(default='', verbose_name='\u5185\u5bb9', blank=True)), ], ), migrations.CreateModel( name='tb_device', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('sh_id', models.IntegerField(db_index=True)), ('sh_name', models.CharField(max_length=50)), ('sh_tags', models.CharField(max_length=50)), ('sh_locate', models.CharField(max_length=50)), ('sh_user_id', models.IntegerField()), ('sh_create_time', models.DateField()), ('sh_last_active', models.DateField()), ('sh_status', models.BooleanField(default=False)), ('sh_about', DjangoUeditor.models.UEditorField(default='', verbose_name='\u5185\u5bb9', blank=True)), ], ), migrations.CreateModel( name='tb_sensor', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('sh_id', models.IntegerField(db_index=True)), ('sh_name', models.CharField(max_length=50)), ('sh_tags', models.CharField(max_length=50)), ('sh_type', models.IntegerField()), ('sh_device_id', models.IntegerField()), ('sh_last_update', models.DateField()), ('sh_last_data', models.TextField()), ('sh_status', models.BooleanField(default=False)), ('sh_about', DjangoUeditor.models.UEditorField(default='', verbose_name='\u5185\u5bb9', blank=True)), ], ), migrations.CreateModel( name='tb_sensor_type', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('sh_id', models.IntegerField(db_index=True)), ('sh_name', models.CharField(max_length=50)), ('sh_description', models.TextField()), ('sh_status', models.BooleanField(default=False)), ], ), migrations.CreateModel( name='tb_user', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('sh_id', models.IntegerField(db_index=True)), ('sh_username', models.CharField(max_length=20)), ('sh_password', models.CharField(max_length=100)), ('sh_email', models.CharField(max_length=50)), ('sh_token', models.CharField(max_length=50)), ('sh_token_exptime', models.DateField()), ('sh_regtime', models.DateField()), ('sh_status', models.BooleanField(default=False)), ('sh_apikey', models.CharField(max_length=100)), ('sh_about', DjangoUeditor.models.UEditorField(default='', verbose_name='\u5185\u5bb9', blank=True)), ], ), migrations.CreateModel( name='tb_user_token', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('sh_user_id', models.IntegerField(db_index=True)), ('sh_token', models.CharField(max_length=100)), ('sh_deadline', models.IntegerField()), ], ), ]
{"/home/admin.py": ["/home/models.py"], "/need_install/Django-1.8.17/tests/fixtures_migration/tests.py": ["/need_install/Django-1.8.17/tests/fixtures_migration/models.py"], "/home/views.py": ["/home/models.py"]}
45,258
MulticsYin/MulticsSH
refs/heads/master
/need_install/Django-1.8.17/tests/template_tests/syntax_tests/test_ssi.py
from __future__ import unicode_literals import os from django.template import Context, Engine from django.test import SimpleTestCase, ignore_warnings from django.utils.deprecation import ( RemovedInDjango19Warning, RemovedInDjango110Warning, ) from ..utils import ROOT, setup @ignore_warnings(category=RemovedInDjango110Warning) class SsiTagTests(SimpleTestCase): # Test normal behavior @setup({'ssi01': '{%% ssi "%s" %%}' % os.path.join( ROOT, 'templates', 'ssi_include.html', )}) def test_ssi01(self): output = self.engine.render_to_string('ssi01') self.assertEqual(output, 'This is for testing an ssi include. {{ test }}\n') @setup({'ssi02': '{%% ssi "%s" %%}' % os.path.join( ROOT, 'not_here', )}) def test_ssi02(self): output = self.engine.render_to_string('ssi02') self.assertEqual(output, ''), @setup({'ssi03': "{%% ssi '%s' %%}" % os.path.join( ROOT, 'not_here', )}) def test_ssi03(self): output = self.engine.render_to_string('ssi03') self.assertEqual(output, ''), # Test passing as a variable @ignore_warnings(category=RemovedInDjango19Warning) @setup({'ssi04': '{% load ssi from future %}{% ssi ssi_file %}'}) def test_ssi04(self): output = self.engine.render_to_string('ssi04', { 'ssi_file': os.path.join(ROOT, 'templates', 'ssi_include.html') }) self.assertEqual(output, 'This is for testing an ssi include. {{ test }}\n') @ignore_warnings(category=RemovedInDjango19Warning) @setup({'ssi05': '{% load ssi from future %}{% ssi ssi_file %}'}) def test_ssi05(self): output = self.engine.render_to_string('ssi05', {'ssi_file': 'no_file'}) self.assertEqual(output, '') # Test parsed output @setup({'ssi06': '{%% ssi "%s" parsed %%}' % os.path.join( ROOT, 'templates', 'ssi_include.html', )}) def test_ssi06(self): output = self.engine.render_to_string('ssi06', {'test': 'Look ma! It parsed!'}) self.assertEqual(output, 'This is for testing an ssi include. ' 'Look ma! It parsed!\n') @setup({'ssi07': '{%% ssi "%s" parsed %%}' % os.path.join( ROOT, 'not_here', )}) def test_ssi07(self): output = self.engine.render_to_string('ssi07', {'test': 'Look ma! It parsed!'}) self.assertEqual(output, '') # Test space in file name @setup({'ssi08': '{%% ssi "%s" %%}' % os.path.join( ROOT, 'templates', 'ssi include with spaces.html', )}) def test_ssi08(self): output = self.engine.render_to_string('ssi08') self.assertEqual(output, 'This is for testing an ssi include ' 'with spaces in its name. {{ test }}\n') @setup({'ssi09': '{%% ssi "%s" parsed %%}' % os.path.join( ROOT, 'templates', 'ssi include with spaces.html', )}) def test_ssi09(self): output = self.engine.render_to_string('ssi09', {'test': 'Look ma! It parsed!'}) self.assertEqual(output, 'This is for testing an ssi include ' 'with spaces in its name. Look ma! It parsed!\n') @ignore_warnings(category=RemovedInDjango110Warning) class SSISecurityTests(SimpleTestCase): def setUp(self): self.ssi_dir = os.path.join(ROOT, "templates", "first") self.engine = Engine(allowed_include_roots=(self.ssi_dir,)) def render_ssi(self, path): # the path must exist for the test to be reliable self.assertTrue(os.path.exists(path)) return self.engine.from_string('{%% ssi "%s" %%}' % path).render(Context({})) def test_allowed_paths(self): acceptable_path = os.path.join(self.ssi_dir, "..", "first", "test.html") self.assertEqual(self.render_ssi(acceptable_path), 'First template\n') def test_relative_include_exploit(self): """ May not bypass allowed_include_roots with relative paths e.g. if allowed_include_roots = ("/var/www",), it should not be possible to do {% ssi "/var/www/../../etc/passwd" %} """ disallowed_paths = [ os.path.join(self.ssi_dir, "..", "ssi_include.html"), os.path.join(self.ssi_dir, "..", "second", "test.html"), ] for disallowed_path in disallowed_paths: self.assertEqual(self.render_ssi(disallowed_path), '')
{"/home/admin.py": ["/home/models.py"], "/need_install/Django-1.8.17/tests/fixtures_migration/tests.py": ["/need_install/Django-1.8.17/tests/fixtures_migration/models.py"], "/home/views.py": ["/home/models.py"]}
45,259
MulticsYin/MulticsSH
refs/heads/master
/need_install/Django-1.8.17/tests/utils_tests/test_tzinfo.py
import copy import datetime import os import pickle import time import unittest import warnings from django.test import ignore_warnings from django.utils.deprecation import RemovedInDjango19Warning # Swallow the import-time warning to test the deprecated implementation. with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=RemovedInDjango19Warning) from django.utils.tzinfo import FixedOffset, LocalTimezone @ignore_warnings(category=RemovedInDjango19Warning) class TzinfoTests(unittest.TestCase): @classmethod def setUpClass(cls): super(TzinfoTests, cls).setUpClass() cls.old_TZ = os.environ.get('TZ') os.environ['TZ'] = 'US/Eastern' try: # Check if a timezone has been set time.tzset() cls.tz_tests = True except AttributeError: # No timezone available. Don't run the tests that require a TZ cls.tz_tests = False @classmethod def tearDownClass(cls): if cls.old_TZ is None: del os.environ['TZ'] else: os.environ['TZ'] = cls.old_TZ # Cleanup - force re-evaluation of TZ environment variable. if cls.tz_tests: time.tzset() super(TzinfoTests, cls).tearDownClass() def test_fixedoffset(self): self.assertEqual(repr(FixedOffset(0)), '+0000') self.assertEqual(repr(FixedOffset(60)), '+0100') self.assertEqual(repr(FixedOffset(-60)), '-0100') self.assertEqual(repr(FixedOffset(280)), '+0440') self.assertEqual(repr(FixedOffset(-280)), '-0440') self.assertEqual(repr(FixedOffset(-78.4)), '-0118') self.assertEqual(repr(FixedOffset(78.4)), '+0118') self.assertEqual(repr(FixedOffset(-5.5 * 60)), '-0530') self.assertEqual(repr(FixedOffset(5.5 * 60)), '+0530') self.assertEqual(repr(FixedOffset(-.5 * 60)), '-0030') self.assertEqual(repr(FixedOffset(.5 * 60)), '+0030') def test_16899(self): if not self.tz_tests: return ts = 1289106000 # Midnight at the end of DST in US/Eastern: 2010-11-07T05:00:00Z dt = datetime.datetime.utcfromtimestamp(ts) # US/Eastern -- we force its representation to "EST" tz = LocalTimezone(dt + datetime.timedelta(days=1)) self.assertEqual( repr(datetime.datetime.fromtimestamp(ts - 3600, tz)), 'datetime.datetime(2010, 11, 7, 0, 0, tzinfo=EST)') self.assertEqual( repr(datetime.datetime.fromtimestamp(ts, tz)), 'datetime.datetime(2010, 11, 7, 1, 0, tzinfo=EST)') self.assertEqual( repr(datetime.datetime.fromtimestamp(ts + 3600, tz)), 'datetime.datetime(2010, 11, 7, 1, 0, tzinfo=EST)') def test_copy(self): now = datetime.datetime.now() self.assertIsInstance(copy.copy(FixedOffset(90)), FixedOffset) self.assertIsInstance(copy.copy(LocalTimezone(now)), LocalTimezone) def test_deepcopy(self): now = datetime.datetime.now() self.assertIsInstance(copy.deepcopy(FixedOffset(90)), FixedOffset) self.assertIsInstance(copy.deepcopy(LocalTimezone(now)), LocalTimezone) def test_pickling_unpickling(self): now = datetime.datetime.now() self.assertIsInstance(pickle.loads(pickle.dumps(FixedOffset(90))), FixedOffset) self.assertIsInstance(pickle.loads(pickle.dumps(LocalTimezone(now))), LocalTimezone)
{"/home/admin.py": ["/home/models.py"], "/need_install/Django-1.8.17/tests/fixtures_migration/tests.py": ["/need_install/Django-1.8.17/tests/fixtures_migration/models.py"], "/home/views.py": ["/home/models.py"]}