반응형


1. 설치

pip install fastapi uvicorn 

pip install aiofiles # CSS파일 로딩 

pip install jinja2


2. Project 구성

3. 시작명령어

python app.py


4. app.py

import uvicorn from fastapi 
import FastAPI, Request from fastapi.responses 
import HTMLResponse 
from fastapi.staticfiles import StaticFiles 
from fastapi.templating import Jinja2Templates 

app = FastAPI() 
templates = Jinja2Templates(directory="templates") 
app.mount("/static", StaticFiles(directory="static"), name="static") 

@app.get('/') 
def hello_world(): 
	return {'message':'hello'} 

@app.get("/items/{id}", response_class=HTMLResponse) 
async def read_item(request: Request, id: str): 
	return templates.TemplateResponse("item.html", {"request": request, "id":id}) 

if __name__ == '__main__': uvicorn.run(app)


5. /tcmplates/item.html

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <title>Item Details</title> 
    <link href="{{ url_for('static', path='/styles.css') }}" rel="stylesheet"> 
</head> 
<body> 
    <img src="{{ url_for('static', path='/fastapi.png') }}" alt="FastAPI"> 
    <h1>is awesome!</h1> 
    <p>Path for item ID: {{ id }}</p> 
</body> 
</html>


6./static/styles.css

h1{ 
	color: red; text-align: center; 
} 

img { 
  	display: block; 
  	margin-left: auto; 
  	margin-right: auto; 
  	width: 50%; 
}

 

반응형

'Programming > Python_Web' 카테고리의 다른 글

FastAPI - MySQL CRUD  (0) 2021.09.10
FastAPI 시작하기  (0) 2021.09.09
Flask강좌6 - 등록/로그인/로그아웃  (0) 2020.12.04
Flask강좌5 - Flask form입력  (0) 2020.12.03
Flask강좌4 - Flask_SQLAlchemy MySQL연동  (5) 2020.12.02
반응형
import folium as g

g_map = g.Map(location=[34.5, 128], zoom_start=7) # tiles='Stamen Terrain', 'Stamen Toner', 'Stamen Watercolor'
latlon=[
        [33.452278, 126.567803],#제주
        [37.56667, 126.97806], #서울
        [35.17944, 129.07556], #부산
       ]

# 마커
marker = g.Marker([37.509671, 127.055517], # 마커를 찍는 과정이다. 해당 위치의  마커를 찍고
                 popup='campus seven', # 해당 마커의 이름을 넣어준다.
                 icon = g.Icon(color='blue'))# 해당 아이콘의 색깔을 지정해준다.
marker.add_to(g_map) # 마지막으로 위에 만들었던 맵에다가 marker를 add 해준다.

# 서클
for i in range(len(latlon)):
    g.Circle(
        location = latlon[i],
        radius = 50,
        color = '#000000',
        fill ='crimson',
    ).add_to(g_map)

# 서클마커    
for j in range(len(latlon)):
    g.CircleMarker(
        latlon[j], # CircleMarker를 통해 원형으로 보이게 한다.
        radius=70,		# 범위
        color='skyblue',	# 선 색깔
        popup='campus seven', # 원의 의름
        fill_color = 'skyblue' # 채워질 원의 색깔
     ).add_to(g_map)


g_map

반응형
반응형

1. vue/cli 설치

npm i -g @vue/cli

 

2. 프로젝트 생성

vue create . //해당 폴더에 생성

 

3. 라이브러리 설치

npm i -g reset-css
npm i vuex@next

4. App.js

<template>
  <div id="app">
    <h1 id="app-title">Fruits List</h1>
    <div id="fruits-table">
      <FruitsList></FruitsList>
      <FruitsPrice></FruitsPrice>
    </div>
  </div>
</template>

<script>
// import HelloWorld from './components/HelloWorld.vue'
// import Mycom from './components/Mycom.vue';
import FruitsList from './components/FruitList.vue'
import FruitsPrice from './components/FruitPrice.vue'

export default {
  name: 'App',
  components: {
    FruitsList,
    FruitsPrice,
  }
}
</script>

<style>
  @import url("css/app.css");
</style>

 

5. /components/FruitList.vue

<!--FruitsList.vue-->
<template>
  <div id="fruits-list">
    <h1>Fruits Name</h1>
    <ul>
      <li v-for="fruit in fruits" :key=fruit>
        {{ fruit.name }}
      </li>
    </ul>
  </div>
</template>

<script>
  export default {
    // Removed Props
    computed: {
      fruits() {
        return this.$store.state.fruits
      }
    }
  }
</script>

<style></style>

 

6. /components/FruitPrice.vue

<!--FruitsPrice.vue-->
<template>
  <div id="fruits-price">
    <h1>Fruits Price</h1>
    <ul>
      <li v-for="fruit in fruits" :key="fruit">
        $ {{ fruit.price }}
      </li>
    </ul>
  </div>
</template>

<script>
  export default {
    // Removed props
    computed: {
      fruits() {
        return this.$store.state.fruits
      }
    }
  }
</script>

<style></style>

 

7. store/store.js

// store.js

import  {createStore} from 'vuex';


//export const store = createStore({
export default createStore({
  // 상태
  state: {
    fruits: [
      { name: 'Apple', price: 30 },
      { name: 'Banana', price: 40 },
      { name: 'Mango', price: 50 },
      { name: 'Orange', price: 60 },
      { name: 'Tomato', price: 70 },
      { name: 'Pineapple', price: 80 }
    ]
  }
});

8. main.js

import { createApp } from 'vue'
import App from './App.vue'
import { store } from './store/store.js'

createApp(App)
.use(store)
.mount('#app')

9. App.css

reset.css가 잘 안불러와질 때가 있네요. 설정 고치는 일이 어려워 일단 생략하고 진행합니다.

/*app.css*/
/* @import url("~reset-css/reset.css"); */
#app-title {
  color: orangered;
  font-size: 40px;
  font-weight: bold;
  text-align: center;
  padding: 40px 0 20px 0;
}
.fruits-table {
  max-width: 700px;
  margin: 0 auto;
  display: flex;
  text-align: center;
  padding: 0 20px;
}
.fruits-table li {
  padding: 20px;
  border-bottom: 1px dashed grey;
  color: white;
  list-style: none;
}
.fruits-table li:last-child { border-bottom: none; }
.fruits-table li:hover { background: rgba(255,255,255,.2); }

#fruits-list {
  background: orange;
  flex: 1;
}
#fruits-price {
  background: tomato;
  flex: 1;
}
#fruits-list h1,
#fruits-price h1 {
  font-weight: bold;
  font-size: 20px;
  padding: 20px;
  border-bottom: 1px solid;
}

반응형
반응형

1. 라이브러리 설치

yarn add redux react-redux @reduxjs/tookit

 

2. index.js

Reducer 연결 및 store 생성

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";

import { configureStore } from "@reduxjs/toolkit";
import rootReducer from "./reducers";
import { Provider } from "react-redux";

const store = configureStore({ 
    reducer: rootReducer,
    devTools: process.env.NODE_ENV !== "production",
});

ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>,
  document.getElementById("root")
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

 

3. App.js

import React from "react";
import "./App.css";
import Counter from './components/Counter';

const App = () => {
  return (
    <div>
      <Counter />
    </div>
  );
};
export default App;

4. reducers/counter.js

import { createAction, createReducer } from "@reduxjs/toolkit";

const INCREASE = "counter/INCREASE";
const DECREASE = "counter/DECREASE";

export const increase = createAction(INCREASE);
export const decrease = createAction(DECREASE);

const initialState = {
  number: 0,
};

const counter = createReducer(initialState, {
  [INCREASE]: (state, action) => ({ number: state.number + 1 }),
  [DECREASE]: (state, action) => ({ number: state.number - 1 }),
});

export default counter;

 

5.reducers/index.js

import { combineReducers } from "redux";
import counter from './counter';

const rootReducer = combineReducers({
  counter,
})

export default rootReducer;

6. components/Counter.jsx

import React from "react";
import { increase, decrease } from "../reducers/counter";
import { useSelector, useDispatch } from "react-redux";

const Counter = () => {
  
  const number = useSelector((state) => state.counter.number);
  const dispatch = useDispatch();
  return (
    <div>
      <h1>{number}</h1>
      <div>
        <button onClick={() => dispatch(increase())}>+1</button>
        <button onClick={() => dispatch(decrease())}>-1</button>
      </div>
    </div>
  );
};

export default Counter;
반응형
반응형

1. 지도에서 좌표-주소 변환

geocoder 라는 것을 사용해야하는데, services라이브러리를 써야합니다. 라이브러리는 api 요청할 때 url에 추가해서 보내면 됩니다. (kakao 예제에서 제공하는 cluster, drawing도 함께 추가해 넣었습니다.)

<script type="text/javascript" src="//dapi.kakao.com/v2/maps/sdk.js?appkey=내api키&libraries=services,clusterer,drawing"></script>

 

2. 우선 화면에 무언가 표시를 해봅시다.

예제는 kakao에서 제공되는 kakao 제주 사옥을 찾는 것 같습니다.

</src/container/MapContainer.js>

import React, { useEffect } from 'react';

const { kakao } = window;

const MapContainer = () => {

  useEffect(() => {
    const container = document.getElementById('myMap');
    const options = {
      center: new kakao.maps.LatLng(35.12, 129.1),
      level: 3
    };
    // 지도를 생성합니다.
    const map = new kakao.maps.Map(container, options);
    // 주소-좌표 변환 객체를 생성합니다.
    const geocoder = new kakao.maps.services.Geocoder();
    // 주소로 좌표를 검색합니다..
    geocoder.addressSearch('제주특별자치도 제주시 첨단로 242', function (result, status) {

      // 정상적으로 검색이 완료됐으면 
      if (status === kakao.maps.services.Status.OK) {
  
        var coords = new kakao.maps.LatLng(result[0].y, result[0].x);
  
        // 결과값으로 받은 위치를 마커로 표시합니다
        var marker = new kakao.maps.Marker({
          map: map,
          position: coords
        });
  
        // 인포윈도우로 장소에 대한 설명을 표시합니다
        var infowindow = new kakao.maps.InfoWindow({
          content: '<div style="width:150px;color:red;text-align:center;padding:6px 0;">내가 썼지롱</div>'
        });
        infowindow.open(map, marker);
  
        // 지도의 중심을 결과값으로 받은 위치로 이동시킵니다
        map.setCenter(coords);
      }
    })
  }, []);

  return (
    <div id='myMap' style={{
      width: '800px', 
      height: '800px'
    }}></div>
  );
}

export default MapContainer;

<결과>

아직 기능들을 알 수는 없지만, 뭔가 써집니다.

반응형
반응형

1. App key 발급

https://apis.map.kakao.com/web/guide/ 사이트에 접속해서 순서대로 진행합니다.

우선 카카오 개발자사이트 (https://developers.kakao.com) 접속하여 회원가입을 하고,

애플리케이션 추가하기를 통해 앱 생성을 합니다.

생성된 앱(mymap)을 클릭해 들어가면 사용할 수 있는 앱 키가 제공됩니다.

 

이렇게 간단히 앱키 발급이 완료되었습니다.

 

2. Sample React App 생성

리액트 앱을 생성하고, 간단히 소스를 추가해보겠습니다.

 

1) public/index.html

아래 코드를 /public/index.html 파일의 <head> 내부에 붙여넣습니다.

<script type="text/javascript" src="//dapi.kakao.com/v2/maps/sdk.js?appkey=발급받은 APP KEY를 넣으시면 됩니다."></script>

2) 지도를 띄우는 코드 작성

</src/container/MapContainer.js>

import React, { useEffect } from 'react';

const { kakao } = window;

const MapContainer = () => {

  useEffect(() => {
    const container = document.getElementById('myMap');
    const options = {
      center: new kakao.maps.LatLng(33.450701, 126.570667),
      level: 3
    };
    const map = new kakao.maps.Map(container, options);
  }, []);

  return (
    <div id='myMap' style={{
      width: '800px', 
      height: '800px'
    }}></div>
  );
}

export default MapContainer;

</src/App.js>

import './App.css';
import MapContainer from './container/MapContainer';

function App() {
  return (
    <div className="App">
      <header className="App-header">
      <MapContainer />
      </header>
    </div>
  );
}

export default App;

 

3. 결과

반응형
반응형

 

1. 조건이 필요할 때 => 3항 연산자

score > 5 ? 'Good': 'Bad';
// 조건이 true이면 'Good', false이면 'Bad'

2. 조건이 필요할 때 => nullish coalescing

const message = text ?? 'Nothing to display';
//text가 있으면 text, 없으면(null, undefined) 'Nothing to display'

//함수 default parameter : null 인 경우에는 null을 출력
function printMessage(text = 'Nothing to display'){
	console.log(text);
}

// Logical Or ||
leftExpr ?? right Expr
// falsy(null, undefined, false, 0, -0, NaN, "", '', ``)에 right Expr 실행

/* 함수도 할당 가능 */

 

3. Object destructing

const { name, age } = person;
console.log(name, age)

 

4. Spread syntax :

// 기존 object로부터 새로운 object를 작성하기

const item = {type: 'Y', size: 'M'};
const detail = {price: 20, made: 'Korea', gender: 'M'};

// Good
const shirt0 = Object.assign(item, detail);

// Better (spread syntax: 배열도 적용 가능)
const shirt = {...item, ...detail, price: 40};	// 신규 값 할당 가능

 

5. Optional Chaning

// Bad
if(person.job && person.job.title){
	console.log(person.job.title);
}

// Good (Optional Chinaing)
if(person.job?.title){
	console.log(person.job.title);
}

// Better (Optional Chinaing + Nullish coalescing)
const title = person.job?.title ?? 'No job yet';
console.log(title);

 

6. Template Literals ( ` : 백틱 )

console.log(`Hello ${name}, Your current score is : ${score}`);

 

7. Loop가 필요할 때 (For 대신)

// 짝수만 골라, 4를 곱해, 총 합 구하기
const items = [1, 2, 3, 4, 5, 6];
const result = items
	.filter((num) => num %2 ===0)
	.map((num) => num *4)
	.reduce((a, b) => a + b, 0);
    
console.log(result);

 

8. 비동기 처리 (promise => async/await)

// 기존
function displayUser(){
	fetchUser()
    	.then((user) => {
         fetchProfile(user)
         	.then((profile) => {
            	updateUI(user, profile);
         });
});

// 변경
async function displayUser(){
  const user = await fetchUser();
  const profile = await fetchProfile(user);
  updateUI(user, profile);
}

9. 중복 제거

const array = ['dog','cat','doggy','dog','lamb','cat'];
console.log([...new Set(array)]);
반응형
반응형

 

SELECT
       LISTAGG(필드명, 구분자)
       WITHIN GROUP ( ORDER BY 정렬기준필드 ASC 또는 DESC)
FROM 테이블
반응형

'Programming > Database' 카테고리의 다른 글

Oracle 설치 후 계정 생성 및 테이블 생성  (4) 2020.05.21
SQL Developer 설치  (0) 2020.02.17
Join 의 종류와 방법  (0) 2020.01.31

+ Recent posts