반응형

Django runserver 이용하여 실행하기

//윈도우
python manage.py runserver
python manage.py runserver //8888(port)

//Mac
python3 manage.py runserver

 

myproject  > urls.py

"""myproject URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('myapp.urls'))
]

myapp >  urls.py 라우터

 

from django.urls import path
from myapp import views

urlpatterns = [
    path('', views.index),
    path('create/',views.create),
    path('read/<id>/',views.read), #read 함수의 파라미터에 id값 전해줌
    path('delete/', views.delete),
    path('update/<id>/',views.update),
]

 

myapp > views.py

from django.http import HttpResponse
from django.shortcuts import render,redirect
import random
from django.views.decorators.csrf import csrf_exempt

def HTMLTemplate(articleTag, id=None):
    global topics
    contextUI = ''
    if id!=None:
        contextUI = f'''
                <li>
                    <form action="/delete/" method="post">
                        <input type="hidden" name="id" value={id}>
                    <input type="submit" value="delete">
                    </form>
                </li>       
                <li><a href="/update/{id}">update</a></li> 
            '''
    ol = ''
    for topic in topics:
        ol += f'<li><a href="/read/{topic["id"]}">{topic["title"]}</a></li>'
    
    return f'''
    <html>
    <body>
        <h1><a href="/">Django</a></h1>
        <ol>
            {ol}
        </ol>
        {articleTag}
        <ul>
            <li><a href="/create/">create</a></li>
            {contextUI}
        </ul> 
    </body>
    </html>
    '''

nextId = 4
topics = [
    {'id':1, 'title':'routing', 'body':'Routing is ..'},
    {'id':2, 'title':'view', 'body':'View is ..'},
    {'id':3, 'title':'Model', 'body':'Model is ..'}
]
# Create your views here.
def index(request):
    article = '''
    <h2>Welcome</h2>
    Hello, Django
    '''
    return HttpResponse(HTMLTemplate(article))

 
def read(request,id):
    global topics
    article = ''
    for topic in topics:
        if topic['id'] == int(id):
            article = f'<h2>{topic["title"]}</h2>{topic["body"]}'

    return HttpResponse(HTMLTemplate(article, id))




@csrf_exempt
def create(request):
    global nextId
    print("request.method", request.method)
    if request.method == "GET":
        article ='''
            <form action="/create/" method="post">
                <p><input type="text" name="title" placeholder="title"></p>
                <p><textarea name="body" placeholder="body"></textarea></p>
                <p><input type="submit"></p>
            </form>
        '''
        return HttpResponse(HTMLTemplate(article))
    elif request.method == "POST":
        print(request.POST['title'])
        title = request.POST['title']
        body = request.POST['body']
        newTopic = {"id":nextId, "title":title, "body":body}
        topics.append(newTopic)
        url = '/read/'+str(nextId)
        nextId+=1
        return redirect(url)

@csrf_exempt
def delete(request):
    global topics
    if request.method == "POST":
        id = request.POST['id']
        newTopics = []

        for topic in topics:
            if topic['id'] != int(id):
                newTopics.append(topic)
        topics = newTopics
        return redirect('/')

@csrf_exempt
def update(request, id):
    global topics

    if request.method == 'GET':
        for topic in topics:
            if topic['id'] == int(id):
                selectedTopic = {
                    "title" : topic['title'],
                    "body" : topic['body'],
                }
        article =f'''
            <form action="/update/{id}/" method="post">
                <p><input type="text" name="title" value={selectedTopic["title"]}></p>
                <p><textarea name="body">{selectedTopic["body"]}</textarea></p>
                <p><input type="submit"></p>
            </form>
        '''
        return HttpResponse(HTMLTemplate(article, id))
    elif request.method == 'POST':
        title = request.POST['title']
        body = request.POST['body']
        for topic in topics:
            if topic['id'] == int(id):
                topic['title'] = title
                topic['body'] = body
        return redirect(f'/read/{id}')

 

생활코딩 강의

반응형

vscode에서 파이썬 셀레니움 웹드라이버를 이용할 때 바로 꺼지는 현상이 나타났다.

 

웹드라이버 버전이 맞는데도 브라우저가 바로 꺼지는 현상이 나타날 수 있다.

 

알고보니까 vscode에서 컨트롤+F5로 실행 안하고

 

 

 

실행 버튼을 눌러주면 안꺼진다

 

 

'Python' 카테고리의 다른 글

pyinstaller: command not found , pyinstaller 에러  (0) 2021.12.27
os로 파일 위치 구하기  (0) 2021.12.25
Python for-else  (0) 2021.12.23
반응형
python -m PyInstaller practice.py

python -m PyInstaller 파일명.py

 

 

이렇게 하면 될 수도 있다.

'Python' 카테고리의 다른 글

vscode selenium python webdriver 바로 꺼짐 오류  (5) 2022.01.05
os로 파일 위치 구하기  (0) 2021.12.25
Python for-else  (0) 2021.12.23
반응형
import os

current_path = os.path.dirname(__file__) #현재 파일의 위치 반환
image_path = os.path.join(current_path, "images") #image 폴더 위치 반환

background = pygame.image.load(os.path.join(image_path, "background.png"))

절대경로를 일일이 입력해주지 않고

 

os를 이용해서

원하는 파일의 경로를 구하고

os.path.join(경로, 파일명) 을 이용해서

경로를 구해줄 수 있다.

'Python' 카테고리의 다른 글

vscode selenium python webdriver 바로 꺼짐 오류  (5) 2022.01.05
pyinstaller: command not found , pyinstaller 에러  (0) 2021.12.27
Python for-else  (0) 2021.12.23
반응형

python for-else 예시

1.

for i in range(10):
    print(i)

    if i == 5:
        print("find it!")
        break
else:
    print("Can't find")

output---

0
1
2
3
4
5
find it!

 

for i in range(10):
    print(i)

    if i == 11:
        print("find it!")
        break
else:
    print("Can't find")

output

0
1
2
3
4
5
6
7
8
9
Can't find

--------------------

 

이처럼 for-else문을 활용해서

for문에서 특정한 행동을 완료하여 break로 탈출을 했는지 안했는지 판별을 해줄 수 있다.

break를 하지 않는 다면 else에 적혀진 문장을 수행한다.

 

만약 for-else문을 사용하지 않는다면 예시의 두번째를 이렇게 써야한다.

breaked = False
for i in range(10):
    print(i)

    if i == 11:
        print("find it!")
        breaked = True
        break

if not(breaked):
    print("Can't find")

큰 차이는 없고, for else가 익숙하지 않아서 오히려 이 방법이 더 가독성이 좋을 수 있다.

 

 

2.

balls = [1,2,3,4]
weapons = [11,22,3,44]

for ball_idx , ball_val in enumerate(balls):
    print("ball :" , ball_val)
    for weapon_idx , weapon_val in enumerate(weapons):
        print("weapons : ", weapon_val)
        if ball_val == weapon_val:
            print("공과 무기가 충돌")
            break
    else:
        continue
    print("바깥 for 문 break")
    break

이처럼 이중포문에서 for else문을 활용하여

내부 for문에서 break가 일어난다면 바깥 for문도 break가 일어나게하여

이중포문을 모두 종료시킬 수 있다.

 

for-else를 모른다면 bool 변수와 if문을 활용해서 위의 예처럼 종료시킬 수도 있다.

balls = [1,2,3,4]
weapons = [11,22,3,44]

breaked = False
for ball_idx , ball_val in enumerate(balls):
    print("ball :" , ball_val)
    for weapon_idx , weapon_val in enumerate(weapons):
        print("weapons : ", weapon_val)
        if ball_val == weapon_val:
            print("공과 무기가 충돌")
            breaked = True
            break

    if (breaked):
        print("바깥 for 문 break")
        break

위와 아래를 비교했을 때 위가 좀더 깔끔하긴 하다.

알면 좋고, 몰라도 크게 차이는 없어보인다.

 

 

 

#for-else #파이썬

+ Recent posts