728x90

과제를 위해 Django 공부중인데... 한글도 포함 가능하게 slug 를 만들고 그걸로 url 을 지정하려니까 헷갈리는 부분이있어서 검색해봄

 

path() , re_path() 역할 

urlpatterns 에 들어갈 요소를 리턴

 

arguments for path()

path(route, view, kwargs=None, name=None)

 

1) route

자료형 :string 또는 gettext_lazy()

내용 : URL pattern

<> : URL 일부를 캡쳐해서 keyword argument로 view 에 전달

 

ex)

path('bio/<username>/', views.bio, name='bio'),

converter specification 을 포함할 수 있다. 이를테면 <int:section> 요렇게..

 

2) view

자료형: view function 또는 as_view() 의 리턴(class-based view 의 경우) 또는 django.urls.include()

 

 

3) kwargs

view function 이나 method 에 추가적인 argument 를 넘길 수 있게 해준다.

 

 

arguments for re_path()

re_path(route, view, kwargs=None, name=None)

1) route

자료형 : Python 의 re 모듈 정규식을 포함하는 string / gettext_lay()

string 은 raw string syntax (r'') 을 사용하며 이때는 \문자의 escape 를 위한 \ 가 추가로 필요하지 않음

route 가 $로 끝나는 경우, 전체 요청 URL은 regular expression pattern 과 일치해야한다.

>> 사실 이 말이 이해가 잘 안됐는데 아래는 이해하도록 도와준 링크...

 

2), 3) 은 path()의 설명과 동일함..

 

 

출처 :https://docs.djangoproject.com/en/4.0/ref/urls/#module-django.urls.conf

 

Django

The web framework for perfectionists with deadlines.

docs.djangoproject.com

 

728x90
728x90

현재 플라스크를 공부하다가

SQL 개념을 안다고 가정하고 진행하는 부분이 있어 생활코딩 강의를 틈틈히끝까지들었다

 

졸릴때마다 멍멍이들이 깨워주었다....

 

암튼 음

 

파이썬을 터미널로 실행 시 가상환경 쓰는법은 알겠는데

파이참으로 코딩할 때 가상환경에 있는 패키지들이 자동으로 불러오기가 안돼서..?

 

실행환경을 그 가상환경으로 고정하고 불러와서 쓰는방법이있을거같은데... 해서 검색해보니

 

1. file > settings > Project > Python Interpreter  

에서 톱니 모양을 누르고..

 

2. 사용할 가상환경 경로를 선택해준다...

../[venv]/bin/python

 

 

원했던대로 가상환경에 인스톨한 패키지가 자동완성이 된당 ㅎㅎㅎ 만족

728x90
728x90

오늘은 지난번에 적어본 코드 실행해보기부터 시작...

 

1. 가상환경 on

 

$ source ./[venv이름]/bin/activate

 

2. 환경변수 설정 (실행할 파이썬 파일 지정)

 

$ export FLASK_APP = [파이썬 파일명 .py 빼고 or 프로젝트 디렉터리명]

 

3. 실행

 

$ flask run

 

오늘 새로 해본 내용

 

개발자모드로 실행하기 > 경고 안뜨고 디버깅모드 온..

export FLASK_ENV=development

( = 앞뒤로 띄어쓰기 넣었더니 에러났음...ㅜ)

 

프로젝트 구조

 

 

728x90
728x90

Play.Kotlin 의 예시코드중 자주 볼 것들을 가져왔음...

출처 : https://play.kotlinlang.org/byExample/05_Collections/

 

Kotlin Playground: Edit, Run, Share Kotlin Code Online

 

play.kotlinlang.org

 

1. filter : 조건을 람다로넣어주면 모든 element 를 확인해 true 값만 들어간 collection 을 return

val numbers = listOf(1, -2, 3, -4, 5, -6)      // 1

val positives = numbers.filter { x -> x > 0 }  // 2

val negatives = numbers.filter { it < 0 }      // 3

 

result

Numbers: [1, -2, 3, -4, 5, -6]
Positive Numbers: [1, 3, 5]
Negative Numbers: [-2, -4, -6]

 

 

 

2. map : collection 의 한 종류인 Map 과 다른것이다.... (왜 이름을 이렇게...?)

람다로 받은 변형을 모든 element에 적용시킨 collection 을 return

val numbers = listOf(1, -2, 3, -4, 5, -6)     // 1

val doubled = numbers.map { x -> x * 2 }      // 2

val tripled = numbers.map { it * 3 }          // 3

 result

Numbers: [1, -2, 3, -4, 5, -6]
Doubled Numbers: [2, -4, 6, -8, 10, -12]
Tripled Numbers: [3, -6, 9, -12, 15, -18]

 

3. any, all, none

: 셋은 Boolean 을 return 한다.

람다로 받은 식을 만족하는 element 가 

any : 하나라도 true이면 true

all : 전부 true 이면 true

none : 하나도 없으면 true

를 return 한다.

 

any 만 예시를..

val numbers = listOf(1, -2, 3, -4, 5, -6)            // 1

val anyNegative = numbers.any { it < 0 }             // 2

val anyGT6 = numbers.any { it > 6 }

 

result

Numbers: [1, -2, 3, -4, 5, -6]
Is there any number less than 0: true
Is there any number greater than 6: false

 

 

모든 코드는 위 출처 사이트에서 확인할 수 있고

Kotlin Playground 에서 편집도 해볼 수 있다...

 

 

728x90
728x90

나는 C++로 상속을 배웠는데

개념적으로 너무 새롭거나 하기보다는 비슷하게느껴졌다.

 

코틀린 상속의 특징

 

1. 클래스도 메서드도 모두 상속 불가(final) 가 Default

open 을 붙여주면 상속가능

 

2. override 시 override 라고 앞에 붙여줌

 

3. 클래스 선언 시 부모클래스 뒤에 파라미터가 없으면 기본 생성자가 호출되고 파라미터를 넘길 수 도 있다.

 

 

실습해본 코드

 

Inheritance.kt

class Inheritance {
	// 1
    class Human()        // default : final 상속불가
    open class Animal(val species : String, val name : String)     // 상속가능
    {
        open fun whoAreYou() {
            println("I am $name, a $species")
        }
    }

	// 2, 3
    class Dog(name : String) : Animal(species = "Dog", name = name)

    class Cat(name: String) : Animal(species = "Cat", name = name)
    {
        override fun whoAreYou() {
            println("I am $name, a $species Meow meow")
        }
    }

}

 

Main.kt

import Inheritance

fun main() {
    val lola = Inheritance.Dog("Lola")
    lola.whoAreYou()
    val inky = Inheritance.Cat("Inky")
    inky.whoAreYou()
}

 

 

출처 : https://play.kotlinlang.org/byExample/01_introduction/07_Inheritance

728x90
728x90

위 에러는 non-null 로 정해진 함수 파라미터에 null 이 들어갔을 때 발생하는 에러이다.

본인이 작성한 함수나 API 에 input 이 non-nullable 인데 null 을 넣었는지 확인해보면 된다...

 

일부러 에러를 유도해보았음

        var neverNull: String = "This can't be null"
        // Default : Non-nullable

        neverNull = null
        // This line causes error
        // "Null can not be a value of a non-null type String"

:String 을 넣지 않아도 위 코드는 에러를 유도한다. non-nullable 이 default 이므로....

 

에러를 없애려면

var nullable : String? = "You can keep null here"
nullable = null

선언 시 자료형 뒤에 ? 붙여주면 됨..

 

 

 

Null Safety 간단 정리

 

1. 코틀린 변수의 default설정은 모든 변수에 null 을 assign 할 수 없다는 것이다.

 

2. null 을 assign 하기 위해서는 ?를 더해주어야 한다.

 

3. 함수 인풋인자로도 nullable / non-nullable 을 명시할 수 있다.

역시 default 는 non-nullable

non-nullable 인자가 들어가는 자리에 nullable 변수를 넣으면 Type Mismatch Error가 발생한다.

 

4. 조건문을 이용한 null tracking 도 가능하다.

 

직접 작성해 본 예시 코드 전문

 

class NullSafety {
    fun example(): Unit{
        var neverNull: String = "This can't be null"
        // Default : Non-nullable

        //neverNull = null
        // This line causes error
        // "Null can not be a value of a non-null type String"

        var nullable : String? = "You can keep null here"
        nullable = null

        println("var neverNull : String")
        println(isItNull(neverNull))
        println("var nullable : String?")
        println(isItNull(nullable))
    }


    // working with Nulls
    // Null tracking using condition
    fun isItNull(maybeString:String?) : String {
        if (maybeString != null)
        {
            return "\t\"$maybeString\"\nIt is not Null"
        } else {
            return "It is Null"
        }
    }
    
}

 

Main.kt

import NullSafety

fun main() {
    NullSafety().example()
}

 

 

출처는 공식사이트의 Kotlin Examples 

https://play.kotlinlang.org/byExample/01_introduction/04_Null%20Safety

728x90
728x90

혼자 공부하면서 메모한 내용...

 

 

1. 가상환경설정

python3 -m venv [venv이름]

./[venv이름]/bin/activate

 

가상환경 실행

source . [venv이름]/bin/activate

 

2.Flask 설치

 

pip install Flask

 

3.예제1 - helloworld

 

# python 코드 내부


from flask import Flask


app = Flask(__name__)


@app.route("/")

def hello_world():

return "<p>Hello, World!</p>"

 

4.routing

root : "/"

project는 "/project/"

/project 입력시에도 자동으로 변환 됨

end point는 "/point"

자동변환 x

 

5.실행 (debugging only)

 

export FLASK_APP=[python 파일이름, 확장자없이]

flask run

 

6. Port

default port  : 5000

포트변경

export FLASK_RUN_PORT=8000

 

포트에러(다른 프로그램이 사용중)

  • OSError: [Errno 98] Address already in use
  • OSError: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions

해당 포트 사용중인 프로세스 찾아내기

$ netstat -nlp | grep 5000

 

7.배포(나중을위해 링크만..)

https://flask.palletsprojects.com/en/2.0.x/deploying/

1. 디버깅모드 해제

2. 옵션 --host=0.0.0.0

(listen to all public IPs)

 

 

 

8.developement features 사용하기

export FLASK_ENV=development

 

9.변수

<var_name>

 

</post/int:var_name>

 

자료형을 추가하면 convert 해줌

 

string / int / float / path(accept '/' ) / uuid

 

 

10. POST/GET

@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
return "post"
else:
return "get"

 

11.Response

string : response body = string, status = 200 OK

 

dictionary : jsonift 호출

 

make_response() 함수 ok

 

 

 

 

728x90
728x90

문제 링크 : https://leetcode.com/problems/first-bad-version/

 

First Bad Version - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

 

기본적인 바이너리 서치 문제이나

오버플로우를 주의해야한다...

 

기본적으로 풀이는,

1. 검색 범위의 맨 앞(min 또는 left) 맨뒤(max 또는 right) 인덱스를 저장하는 변수를 설정하고

각각 1과 n으로 초기화 한다.

min은 항상 Not bad version,  max 는 항상 bad version 이라고 가정하고 풀었기 때문에

양 끝값 확인하는 절차로 버전1이 배드버전인지 확인하는 코드를 추가로 넣었다.

 

2. 그 가운데인덱스를 API호출로 확인 후

가운데가 Bad version 이면 max 인덱스를 mid로 옮기고, Bad version 이 아닌 경우 min을 mid로 옮긴다.

여기서 중요한것은 중간값을 구할 때

mid = (min + max) / 2 로 구하면 overflow 가 일어날 수 있으므로

mid = min + (max - min)/2 라고 써줘야한다는 것이다.

 

두 수식은 사람눈에는 비슷하지만 컴퓨터가 볼 때는... 두 수의 합이 자료형 사이즈를 넘어버리면 완전히 다른 식이 된다.

 

3. 이렇게 반복하다가 min 과 max 가 만나면

첫번째 Bad version 은 max 이므로 max를 리턴해주면 된다.

 

 

아래는 내 해답

/* The isBadVersion API is defined in the parent class VersionControl.
      def isBadVersion(version: Int): Boolean = {} */

class Solution: VersionControl() {
    override fun firstBadVersion(n: Int) : Int {
        var min = 1
        var max = n
        var mid : Int
        if(isBadVersion(min)) return 1
        
        while(min+1 < max) {
            mid = min + (max-min)/ 2
            if(isBadVersion(mid)) 
            {
                max = mid
            } else {
                min = mid
            }
        }
        return max
	}
}

 

 

isBadVersion API 가 구현이 안 된 상태로 코딩을하려니 디버깅이 어려워서 힘들었다....

오래걸릴줄 알았으면 isBadVersion 구현해서 IDE 디버거를 썼을텐데

흠 개쉽군 하고 그냥 릿코드 사이트에서 풀다가 1시간은 족히걸렸다.... 힝힝

 

프로그래밍 첫 강의에서 배운 자료형의 사이즈..... 역시 기본이 중요한 것이다....

728x90

+ Recent posts